Saturday, October 3, 2020

What is angular?

 

What is angular?

1. Angular is an open-source Javascript framework developed by Google.

2. Angular is a single page application.

3. Angular compiles typescript code as a javascript code while compiling.

4. Typescript is a primary language for angular, It is secure and cannot be executable.

5. Typescript is developed and maintained by Microsoft.

Tools and components:

1.  Node.js

2. Visual studio code

3. Angular CLI

NPM :

Angular implements a dependency injection design pattern. All dependency downloaded in the Node_Modules folder through the Node Package Manager. For example, you can install jquery, bootstrap using npm install command. Node Package Manager serves your application on the localhost.

Visual Studio Code:

Visual studio code is a lightweight, powerful code editor. You can quickly build, debug, format, and deploy the application. It makes your coding very fast and clean.

Angular CLI :

Angular CLI is a command-line interface tool. We can create component, service, and class through angular CLI. It helps to build your application through the command line.

Basic knowledge required to start angular:

1.  Html

2.  CSS

3.  Typescript

4.  Node.Js (Not mandatory)

 

angular introduction

Angular 8 crud example (Create, Read, Update, Delete)

 In this tutorial, we will learn about achieving crud operation using angular, PHP, MySQL, Rest API. Angular CRUD means nothing; just angular insert, update, delete, select example. If you would like to start to develop any project, you should be familiar with this operation because of all the functionality achieved by using any one this operation. Ok, let’s divide our tutorial into six categories.

  • Database, tables creation in MySQL
  • PHP Rest API for Crud operation
  • Angular UI Components
  • Angular Common files (service, module, routing module)
  • Angular CRUD application functionality
  • All Technical solution

angular 8 crud example

Refer our previous tutorial angular 8 login logout registration example so that you can understand the authentication.Navigation and login logout part covered in previous part. So refer the previous one . Login,logout,route gaurd code everything available in the previous tutorial. This is second part of that one.

Database, tables creation in MySQL:

Create a database in the name of ng and create an employee table as given the below structures.

CREATE TABLE `employee` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `pwd` varchar(100) NOT NULL,
  `email` varchar(60) DEFAULT NULL,
  `mobile` varchar(100) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

 PHP Rest API for Angular Crud operation:

First, create the PHP “config.php” file and code for connecting the database, allow CORS origin.

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
 
  $db_username = 'root';
 $db_password = 'airtel';
 $db_name = 'ng';
 $db_host = 'localhost';				
$mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);
 
if ($mysqli->connect_error) {
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
?>

 Let’s create all rest API to achieve the below functionality.

“getdata.php” - Display all employee list in the Html table.
“getdataone.php” – Select single employee details and set value in textbox while editing the employee Html table.
“registration.php” – getting all textbox value after reactive form validation then insert the record in the employee table.
“deletedata.php” – delete employee records through employee id.
“updateuser.php” – update employee records through employee id.

getdata.php

<?php
include_once("config.php");
 
$sql = "SELECT Id,name,email,pwd,mobile FROM employee";
 
if($result = mysqli_query($mysqli,$sql))
{
 $rows = array();
  while($row = mysqli_fetch_assoc($result))
  {
    $rows[] = $row;
  }
 
  echo json_encode($rows);
}
else
{
  http_response_code(404);
}
?>

getdataone.php

<?php
include_once("config.php");
 
$postdata = file_get_contents("php://input");
$empid=$_GET["empid"];
 
$sql="SELECT Id,name,email,pwd,mobile FROM employee where Id='$empid'";
 
 
if($result = mysqli_query($mysqli,$sql))
{
 $rows = array();
  while($row = mysqli_fetch_assoc($result))
  {
    $rows[] = $row;
  }
 
  echo json_encode($rows);
}
else
{
  http_response_code(404);
}
?>

registration.php

<?php
include_once("config.php");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
  $name = mysqli_real_escape_string($mysqli, trim($request->name));
  $pwd = mysqli_real_escape_string($mysqli, (int)$request->pwd);
   $email = mysqli_real_escape_string($mysqli, trim($request->email));
  $mobile = mysqli_real_escape_string($mysqli, (int)$request->mobile);
  $sql = "INSERT INTO employee(name,pwd,email,mobile) VALUES ('{$name}','{$pwd}','{$email}','{$mobile}')";
 // echo $sql;
if ($mysqli->query($sql) === TRUE) {
 
 
    $authdata = [
      'name' => $name,
	  'pwd' => '',
	  'email' => $email,
      'mobile' => $mobile,
      'Id'    => mysqli_insert_id($mysqli)
    ];
    echo json_encode($authdata);
 
}
}
?>

deletedata.php

<?php
include_once("config.php");
 
 
if($_GET["empid"] !="")
{
 
$empid=$_GET["empid"];
 
  $sql = "delete from employee  WHERE Id = '{$empid}' LIMIT 1";
 
  if(mysqli_query($mysqli, $sql))
  {
    http_response_code(204);
  }
  else
  {
    return http_response_code(422);
  }  
}
?>

updateuser.php

<?php
include_once("config.php");
$postdata = file_get_contents("php://input");
 
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
 
	$id = mysqli_real_escape_string($mysqli, trim($request->id));
	// echo $id;
  $name = mysqli_real_escape_string($mysqli, trim($request->name));
  $pwd = mysqli_real_escape_string($mysqli, (int)$request->pwd);
   $email = mysqli_real_escape_string($mysqli, trim($request->email));
  $mobile = mysqli_real_escape_string($mysqli, (int)$request->mobile);
 
  $sql = "update employee set name='$name',pwd='$pwd',email='$email',mobile='$mobile' where Id=$id";
 //echo $sql;
if ($mysqli->query($sql) === TRUE) {
 
 
    $authdata = [
      'name' => $name,
	  'pwd' => '',
	  'email' => $email,
      'mobile' => $mobile,
      'Id'    => ''
    ];
    echo json_encode($authdata);
 
}
}
?>

Angular UI Components:

Let’s create the components below.

“dashboard.component” – Display employee list.
“edituser.component” – Edit or update a single employee record.
“createuser.component” – Add or insert new employee records.

dashboard.component.html

 
<div class="container">
  <div class="row">
    <div class="col-md-12">
      <h2 class="text-center" > Employee Details</h2>
      <button class="btn btn-success text-right"  (click)="addUser()"> Add User</button>
      <table class="table table-striped">
        <thead>
        <tr>
 
          <th>ID</th>
          <th>Name</th>
          <th>Mobile</th>
          <th>Email</th>
          <th>Delete</th>
          <th>Edit</th>
        </tr>
        </thead>
        <tbody>
        <tr *ngFor="let user of users">
 
          <td>{{user.Id}}</td>
          <td>{{user.name}}</td>
          <td>{{user.mobile}}</td>
          <td>{{user.email}}</td>
          <td><button class="btn btn-danger" (click)="deleteuserdetails(user)"> Delete</button></td>
            <td>  <button class="btn btn-success" (click)="updateUser(user)" style="margin-left: 20px;"> Edit</button></td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

dashboard.component.ts

import { Component, OnInit } from '@angular/core';
import { DataserviceService } from '../dataservice.service';
import { Usermodule } from '../usermodule';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
 
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  users: Usermodule[];
  cat:number;
 
  constructor(private dataService: DataserviceService,private router:Router) { }
 
  ngOnInit() {
    this.getuserdetails();
 
  }
getuserdetails()
{
  this.dataService.getAllUsers(this.cat).subscribe(response =>
    {
      this.users = response.map(item =>
      {
        return new Usermodule(
          item.Id,
            item.name,
            item.pwd,
            item.email,
            item.mobile,
        );
      });
    });
}
deleteuserdetails(user:Usermodule)
{
  this.dataService.removeEmployee(user.Id)
  .subscribe( data => {
    //this.users = this.users.filter(u => u !== user);
    this.getuserdetails();
  })
 
}
updateUser(user: Usermodule): void {
  window.localStorage.removeItem("editId");
  window.localStorage.setItem("editId", user.Id.toString());
  this.router.navigate(['edit']);
};
addUser(): void {
  this.router.navigate(['create']);
};
}
 

edituser.component.html

<h2 class="text-center">Edit User</h2>
<div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-6 col-md-offset-3">
        <div class="jumbotron">
            <form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off" >
                <div class="form-group">
                    <label for="name">User Name</label>
                    <input type="text" name="name" formControlName="name" autocomplete="off" class="form-control input-sm" placeholder="User Name">
                    <input type="hidden" name="id" formControlName="id"  class="form-control input-sm" >
                </div>
 
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" name="email" formControlName="email" autocomplete="off" class="form-control input-sm" placeholder="Email Address">
 
                </div>
                <div class="form-group">
                    <label for="Password">Password</label>
                    <input type="password" name="Password" formControlName="password"  autocomplete="off" class="form-control input-sm" placeholder="Password">
 
                </div>
                <div class="form-group">
                    <label for="name">Mobile No</label>
                    <input type="text" name="mobile" formControlName="mobile" autocomplete="off" class="form-control input-sm" placeholder="Mobile No">
 
                </div>
                <button type="submit" class="btn btn-primary" [disabled]="!angForm.valid">Update</button>
            </form>
        </div>
    </div>
    <div class="col-md-3">
    </div>
 
</div>

edituser.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm } from '@angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '@angular/router';
import { DataserviceService } from '../dataservice.service';
 
@Component({
  selector: 'app-edituser',
  templateUrl: './edituser.component.html',
  styleUrls: ['./edituser.component.css']
})
export class EdituserComponent implements OnInit {
 
  angForm: FormGroup;
  constructor(private fb: FormBuilder,private dataService: DataserviceService,private router:Router) {
 
    this.angForm = this.fb.group({
      email: ['', [Validators.required,Validators.minLength(1), Validators.email]],
      password: ['', Validators.required],
      name: ['', Validators.required],
      mobile: ['', Validators.required],
      id: ['']
 
    });
   }
 
  ngOnInit() {
    let Id = window.localStorage.getItem("editId");
    if(!Id) {
      this.router.navigate(['list-user']);
      return;
    }
    this.dataService.getUserId(+Id)
      .subscribe( data => {
       // this.angForm.controls[email].setValue('name')
       // this.email.nativeElement.value = 'This is new value';
        this.angForm.patchValue({
          id:data[0].Id,name: data[0].name, email: data[0].email, password: data[0].pwd, mobile: data[0].mobile
 
       });
      });
  }
  postdata(angForm1:NgForm)
  {
    this.dataService.updateuserdetails(angForm1.value.id, angForm1.value.name,angForm1.value.email,angForm1.value.password,angForm1.value.mobile)
 
    .pipe(first())
    .subscribe(
        data => {
            this.router.navigate(['dashboard']);
        },
        error => {
        });
 
  }
  get email() { return this.angForm.get('email'); }
  get password() { return this.angForm.get('password'); }
  get name() { return this.angForm.get('name'); }
  get mobile() { return this.angForm.get('mobile'); }
  get id() { return this.angForm.get('id'); }
 
}
 

createuser.component.html

<h2 class="text-center">Create User</h2>
<div class="row">
    <div class="col-md-3">
    </div>
    <div class="col-md-6 col-md-offset-3">
        <div class="jumbotron">
            <form [formGroup]="angForm" (ngSubmit)="postdata(angForm)" autocomplete="off" >
                <div class="form-group">
                    <label for="name">User Name</label>
                    <input type="text" name="name" formControlName="name" autocomplete="off" class="form-control input-sm" placeholder="User Name">
 
                </div>
 
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" name="email" formControlName="email" autocomplete="off" class="form-control input-sm" placeholder="Email Address">
 
                </div>
                <div class="form-group">
                    <label for="Password">Password</label>
                    <input type="password" name="Password" formControlName="password"  autocomplete="off" class="form-control input-sm" placeholder="Password">
 
                </div>
                <div class="form-group">
                    <label for="name">Mobile No</label>
                    <input type="text" name="mobile" formControlName="mobile" autocomplete="off" class="form-control input-sm" placeholder="Mobile No">
 
                </div>
                <button type="submit" class="btn btn-primary" [disabled]="!angForm.valid">Create</button>
 
            </form>
        </div>
    </div>
    <div class="col-md-3">
    </div>
 
</div>

createuser.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm } from '@angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '@angular/router';
import { DataserviceService } from '../dataservice.service';
 
@Component({
  selector: 'app-createuser',
  templateUrl: './createuser.component.html',
  styleUrls: ['./createuser.component.css']
})
export class CreateuserComponent implements OnInit {
  angForm: FormGroup;
  constructor(private fb: FormBuilder,private dataService: DataserviceService,private router:Router) {
 
    this.angForm = this.fb.group({
      email: ['', [Validators.required,Validators.minLength(1), Validators.email]],
      password: ['', Validators.required],
      name: ['', Validators.required],
      mobile: ['', Validators.required]
 
    });
   }
 
  ngOnInit() {
  }
  postdata(angForm1:NgForm)
  {
    this.dataService.userregistration(angForm1.value.name,angForm1.value.email,angForm1.value.password,angForm1.value.mobile)
      .pipe(first())
      .subscribe(
          data => {
              this.router.navigate(['dashboard']);
          },
          error => {
          });
  }
  get email() { return this.angForm.get('email'); }
  get password() { return this.angForm.get('password'); }
  get name() { return this.angForm.get('name'); }
  get mobile() { return this.angForm.get('mobile'); }
 
}
 

Angular Common files (service, module, routing module):

Let’s create below mentioned most important standard files.

“dataservice.service.ts” file contains all common API function for reuse.
“usermodule.ts” file contains all data entity.
“app.routing.module” file contains all routing configuration.

dataservice.service.ts

import { Injectable, Output, EventEmitter } from '@angular/core';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Usermodule } from './usermodule';
 
@Injectable({
  providedIn: 'root'
})
export class DataserviceService {
  redirectUrl: string;
 
  baseUrl:string = "http://localhost/uat/api";
@Output() getLoggedInName: EventEmitter<any> = new EventEmitter();
  constructor(private httpClient : HttpClient) { }
  public userlogin(username, password) {
    return this.httpClient.post<any>(this.baseUrl + '/login.php', { username, password })
        .pipe(map(Usermodule => {
            this.setToken(Usermodule[0].name);
            this.getLoggedInName.emit(true);
            return Usermodule;
        }));
}
public userregistration(name,email,pwd,mobile) {
  return this.httpClient.post<any>(this.baseUrl + '/registration.php', { name,email, pwd,mobile })
      .pipe(map(Usermodule => {
          return Usermodule;
      }));
}
public updateuserdetails(id,name,email,pwd,mobile) {
  return this.httpClient.post<any>(this.baseUrl + '/updateuser.php', { id,name,email,pwd,mobile })
    .pipe(map(Usermodule => {
          return Usermodule;
      }));
 
}
removeEmployee(empid: number): Observable<Usermodule[]> {
  return this.httpClient.delete<Usermodule[]>(this.baseUrl+'/deletedata.php?empid='+empid );
}
public getUserId(empid: number): Observable<Usermodule[]>
  {
    return this.httpClient.get<Usermodule[]>(
      this.baseUrl + '/getdataone.php?'+ 'empid=' + empid 
      );
  }
 
getAllUsers(id) : Observable<Usermodule[] > {
  return this.httpClient.get<Usermodule[]>(this.baseUrl+'/getdata.php');
}
 
//token
setToken(token: string) {
  localStorage.setItem('token', token);
}
 
getToken() {
  return localStorage.getItem('token');
}
 
deleteToken() {
  localStorage.removeItem('token');
}
 
isLoggedIn() {
  const usertoken = this.getToken();
  if (usertoken != null) {
    return true
  }
  return false;
}
 
}
 

usermodule.ts

export class Usermodule {
    public Id: number;
    public name: string;
    public pwd:string;
    public email:string;
    public mobile:string;
    constructor(Id:number,name: string,pwd:string,email:string,mobile:string) {
      this.Id = Id;
      this.name = name;
      this.pwd = pwd;
      this.email = email;
      this.mobile=mobile;
    }
}
 

app.routing.module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { RegistrationComponent } from './registration/registration.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthguardGuard } from './authguard.guard';
import { CreateuserComponent } from './createuser/createuser.component';
import { EdituserComponent } from './edituser/edituser.component';
 
const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  { path: 'registration', component: RegistrationComponent },
  { path: 'create', component: CreateuserComponent,canActivate: [AuthguardGuard] },
  { path: 'edit', component: EdituserComponent,canActivate: [AuthguardGuard] },
  { path: 'dashboard', component: DashboardComponent,canActivate: [AuthguardGuard] }
 
]
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
 

app.module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule,ReactiveFormsModule } from '@angular/forms'; 
import { HttpClientModule } from '@angular/common/http';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegistrationComponent } from './registration/registration.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { CreateuserComponent } from './createuser/createuser.component';
import { EdituserComponent } from './edituser/edituser.component';
 
@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegistrationComponent,
    DashboardComponent,
    CreateuserComponent,
    EdituserComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
     ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
 

Angular CRUD application functionality: 

Before this section goes through our previous angular tutorial angular login, logout example.

When an employee login the application successfully, the user redirected to the dashboard page, which displays all employee data (Id, name, email, password, mobile). Every row contains an edit and deletes button. 

If you click the edit button, set the employee id as local storage variable “empid” and redirecting to “edituser” component. Now get the employee id from local storage variable on “ngOnInization” event and fetching employee record through employee id.
 Finally, assign to all form control values. Now user can update records through clicking over the update button.
Once edited, the record again redirected the dashboard page. Similarly, user can insert new employee record through Add button.
Delete button through user can remove the particular employee records.

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...