Insert update Delete in Angular.

Hello friends in this article i will show you an example of Insert update Delete in Angular.


Step 1: Create an employee folder in AngularCrud/src/app/

Step 2: Now Create Model folder in employee folder.

Step 3: Now Create employee.ts file in Model folder to create employee model.


     export class employee {
code: number;
name: string;
gender: boolean;
annualSalary: number;
dateOfBirth: Date;
}


Step 4: Now Create Employee.Service.ts under employee Folder to create employee service for http request to call WebApi.
import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
/
import { Observable, of } from 'rxjs';
import { Router } from '@angular/router';

import { employee } from './Model/employee';

@Injectable()
export class EmployeeService {
constructor(private _http: Http) { }
url = "http://localhost:50313/api/Create";

getEmployee() {
debugger
return this._http.get("http://localhost:50313/api/employees")
}

getEmployeeByCode(code) {
debugger
return this._http.get("http://localhost:50313/api/employees/"+code)
}
saveEmployee(Employee:employee) {
debugger
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
var body = JSON.stringify({
code:Employee.code,
name:Employee.name,
gender:Employee.gender,
annualSalary:Employee.annualSalary,
dateOfBirth: Employee.dateOfBirth
})

return this._http.post("http://localhost:50313/api/employees/Add",body)
}

UpdateEmployee(Employee:employee) {
debugger
debugger
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
var body = JSON.stringify({
code:Employee.code,
name:Employee.name,
gender:Employee.gender,
annualSalary:Employee.annualSalary,
dateOfBirth: Employee.dateOfBirth
})
return this._http.post("http://localhost:50313/api/employees/EditEmployee",body)
}
}

Step 5: Now First of all we will select all the employees from WebApi. So we will call getEmployee() Method from  Employee.Service.ts.

Create component employee.component.ts under employee Folder


import { Component, OnInit } from '@angular/core'
import { employee } from './Model/employee';
import { EmployeeService } from './employee.Service';
import { NgForm } from '@angular/forms';

@Component({
templateUrl: './employee.component.html',
providers:[EmployeeService]

})

export class EmployeeComponent implements OnInit

{
employees: employee[];
SelectedEmployeeCountRadioButton: string = 'All';
constructor(private _employeeService: EmployeeService) {
}

ngOnInit() {
debugger
this._employeeService.getEmployee().subscribe(data => {
this.employees=<employee[]>data.json()
})

}


}

Now to display feched employee list we will create eloyee.component.html page Under Employee Folder. 

<table>
<thead>
<tr>
<th>Code</th>
<th>Name</th>
<th>Gender</th>
<th>Annual Salary</th>
<th>Date of Birth</th>
<th>Update</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let employee of employees;">
<tr>
<td><a [routerLink]="['/employees',employee.code]">
{{employee.code }}
</a></td>
<td>{{employee.name }}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary }}</td>
<td>{{employee.dateOfBirth }}</td>
<td>
<td><a [routerLink]="['/Update',employee.code]">
Edit
</a></td>
</tr>
</ng-container>
<!--If the web service takes time to return data, the message in this <tr>
is displayed. When the service call returns this message disappears
and the employees data is displayed-->
<tr *ngIf="!employees">
<td colspan="5">
Loading data. Please wait...
</td>
</tr>
<!--This message is displayed if the web services does not return any data-->
<tr *ngIf="employees && employees.length==0">
<td colspan="5">
No employee records to display
</td>
</tr>
</tbody>
</table>

Now we will add new employee to database. So we need to create CreateEmployee.html  form page to insert new employee Under Employee Folder.


<h1> Create Employee</h1>


<form #employeeForm="ngForm" (ngSubmit)="saveEmployee(employeeForm)">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Create Employee</h3>
</div>
<div class="panel-body">

<div class="form-group"
[class.has-error]="fullNameControl.invalid && fullNameControl.touched"
[class.has-success]="fullNameControl.valid">
<label for="name" class="control-label">Full Name</label>
<input required id="name" type="text" class="form-control"
name="name" [(ngModel)]="Employee.name" #fullNameControl="ngModel">
<span class="help-block" *ngIf="fullNameControl.touched && !fullNameControl.valid">
Name Is required
</span>
</div>



<div class="form-group" >
<label for="email">code</label>
<input id="code" required [email]="Employee.code!==''" type="text"
class="form-control"
name="code" [(ngModel)]="Employee.code" #codeAddress="ngModel">
</div>

<div class="form-group" [class.has-error]="gender1.touched && gender1.invalid">
<label class="control-label"> gender</label>
<div class="form-control">
<label class="radio-inline">
<input type="radio" required #gender1="ngModel" value="male" name="gender"
[(ngModel)]="Employee.gender">male
</label>
<label class="radio-inline">
<input type="radio" required #gender1="ngModel" value="female" name="gender"
[(ngModel)]="Employee.gender">female
</label>
</div>
<span class="help-block" *ngIf="gender1.touched && gender1.invalid">
gender is required
</span>
</div>

<div class="form-group"
[class.has-error]="annualSalaryControl.invalid && annualSalaryControl.touched"
[class.has-success]="annualSalaryControl.valid">
<label for="annualSalary" class="control-label">annualSalary</label>
<input required id="annualSalary" type="text" class="form-control"
name="annualSalary" [(ngModel)]="Employee.annualSalary"
#annualSalaryControl="ngModel">
<span class="help-block"
*ngIf="annualSalaryControl.touched && !annualSalaryControl.valid">
Sallary Is required
</span>
</div>

</div>
<div class="form-group">
<label for="dateOfBirth"> Date of Birth</label>
<input id="dateOfBirth" name="dateOfBirth" [(ngModel)]="Employee.dateOfBirth"
type="date" class="form-control">
</div>
<div class="panel-footer">
<button class="btn btn-primary" type="submit">Save</button>
</div>
</div>
</form>

Angular Generated Form Model: {{employeeForm.value | json}}

Now we will create component to add new employee so we will create a CreateEmployee.component.ts   file  Under Employee Folder..

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './Employee.Service';
import { employee } from './Model/employee';
import { Router, ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
templateUrl: './CreateEmployee.html',
providers: [EmployeeService]

})

export class CreateEmployee implements OnInit {

Employee: employee = {
code: null,
name: null,
gender: null,
annualSalary: null,
dateOfBirth: null
};
errorMessage: any;
SelectedEmployeeCountRadioButton: string = 'All';
constructor(private _employeeService: EmployeeService, private _router: Router) {

}

ngOnInit() {


}
saveEmployee(empForm: NgForm): void {
debugger
this._employeeService.saveEmployee(empForm.value)
.subscribe((data) => {
debugger
this.reset();
},
error => this.errorMessage = <any>error);
}

private reset() {
this.Employee.code= null;
this.Employee.name = null;
this.Employee.gender = null;
this.Employee.annualSalary = null;
this.Employee.dateOfBirth= null;
}
}

Now we will perform update employee operation. So we will create a UpdateEmployee.html  form  Under Employee Folder.


<h1> Update Employee</h1>


<form #employeeForm="ngForm" (ngSubmit)="updateEmployee(employeeForm)">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Create Employee</h3>
</div>
<div class="panel-body">

<div class="form-group"
[class.has-error]="fullNameControl.invalid && fullNameControl.touched"
[class.has-success]="fullNameControl.valid">
<label for="name" class="control-label">Full Name</label>
<input required id="name" type="text" class="form-control"
name="name" [(ngModel)]="Employee.name" #fullNameControl="ngModel">
<span class="help-block" *ngIf="fullNameControl.touched && !fullNameControl.valid">
Name Is required
</span>
</div>



<div class="form-group" >
<label for="email">code</label>
<input id="code" required [email]="Employee.code!==''" type="text"
class="form-control"
name="code" [(ngModel)]="Employee.code" #codeAddress="ngModel">
</div>

<div class="form-group" [class.has-error]="gender1.touched && gender1.invalid">
<label class="control-label"> gender</label>
<div class="form-control">
<label class="radio-inline">
<input type="radio" required #gender1="ngModel" value="male" name="gender"
[(ngModel)]="Employee.gender">male
</label>
<label class="radio-inline">
<input type="radio" required #gender1="ngModel" value="female" name="gender"
[(ngModel)]="Employee.gender">female
</label>
</div>
<span class="help-block" *ngIf="gender1.touched && gender1.invalid">
gender is required
</span>
</div>

<div class="form-group"
[class.has-error]="annualSalaryControl.invalid && annualSalaryControl.touched"
[class.has-success]="annualSalaryControl.valid">
<label for="annualSalary" class="control-label">annualSalary</label>
<input required id="annualSalary" type="text" class="form-control"
name="annualSalary" [(ngModel)]="Employee.annualSalary"
#annualSalaryControl="ngModel">
<span class="help-block"
*ngIf="annualSalaryControl.touched && !annualSalaryControl.valid">
Sallary Is required
</span>
</div>

</div>
<div class="form-group">
<label for="dateOfBirth"> Date of Birth</label>
<input id="dateOfBirth" name="dateOfBirth"
[(ngModel)]="Employee.dateOfBirth" type="date" class="form-control">
</div>
<div class="panel-footer">
<button class="btn btn-primary" type="submit">Save</button>
</div>
</div>
</form>

Angular Generated Form Model: {{employeeForm.value | json}}

Now we will create a component for update employee so we will create UpdateEmployee.component.ts  file  Under Employee Folder..

import { Component, OnInit } from '@angular/core';
import { EmployeeService } from './Employee.Service';
import { employee } from './Model/employee';
import { Router, ActivatedRoute } from '@angular/router';
import { NgForm } from '@angular/forms';


@Component({

templateUrl: './UpdateEmployee.html',
providers: [EmployeeService]

})

export class UpdateEmployee implements OnInit {

Employee: employee = {
code: null,
name: null,
gender: null,
annualSalary: null,
dateOfBirth: null
};
errorMessage: any;
SelectedEmployeeCountRadioButton: string = 'All';
constructor(private _employeeService: EmployeeService, private _activatedRoute: ActivatedRoute) {

}

ngOnInit() {
let empCode: string = this._activatedRoute.snapshot.params['code'];
debugger
this._employeeService.getEmployeeByCode(empCode).subscribe(
data => {
this.Employee=<employee>data.json()

}

);
}

updateEmployee(empForm: NgForm):void
{
debugger
this._employeeService.UpdateEmployee(empForm.value).subscribe((data) => {
debugger
},
error => this.errorMessage = <any>error);
}

}

Now under AngularCrud/src/app/  you will find a file app.component.html. Now Copy bellow content and paste it into your  app.component.html file.

<nav class="navbar navbar-default">
<ul class="navbar navbar-nav">
<li><a routerLink="list">List</a></li>
<li>
<a routerLink="Create">Create</a>
</li>
</ul>
</nav>
<router-outlet></router-outlet>

Now under AngularCrud/src/app/ you will find app.component.ts So copy below code and paste it to your app.component.ts file.

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent { myModel: any; }



Now under AngularCrud/src/app/  you will find app.module.ts file. So copy bellow code and paste it to your  app.module.ts  file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router'


import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';
import { HomeComponent } from './Home/home.component';
import { CreateEmployee } from './employee/CreateEmployee.component';
import { UpdateEmployee } from './employee/UpdateEmployee.component';
import { PageNotFoundComponent } from './Others/pageNotfound.component';

const appRoutes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'list', component: EmployeeComponent },
{ path: 'Create', component: CreateEmployee },
{ path: 'Update/:code', component: UpdateEmployee },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{path:'**', component:PageNotFoundComponent}
];

@NgModule({
imports: [BrowserModule, FormsModule, HttpModule,
RouterModule.forRoot(appRoutes)],
declarations: [AppComponent, EmployeeComponent, HomeComponent,
PageNotFoundComponent, CreateEmployee, UpdateEmployee],
bootstrap:[ AppComponent ]
})
export class AppModule { }

Now under AngularCrud/src/  you will find index.html  file. So copy below code and paste it into your  index.html  file.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularCrud</title>
<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

Comments

Popular posts from this blog

how to save images with angular nodejs

How to add splash screen and app icon with ionic capacitor angular android app