CRUD Operation In Angular 6

Angular 6 CRUD Operation

In this article, we will be building an Angular 6 application and will perform a CRUD Operation step by step from scratch with an example. We will be generating our Angular 6 application using Angular CLI and then modify it to have an employee management project where the end-user can perform CRUD operations, i.e., Create, List, Update, and Delete with the sample REST API exposed using HttpClientModule. We will also be using RouterModule to have the routing enabled.

For this project, I have npm 5.6.0 and node v8.11.2 installed on my local system. You can download the latest version of Node from here. To update NPM, you can run the following command in the terminal.

npm i npm@latest -g

If you have the @angular/cli version older than 6, then run the following command to install the latest version.

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli

To install a specific version, you can use this command - 

npm install -g @angular/[email protected]

Generating Angular 6 Project

Once the npm and node are upgraded to the latest version, you can run the following command to generate an Angular 6 project in any location of your choice.

ng new crudoperation

Doing so, our Angular 6 application is generated.

Angular 6 Project Structure

Once the project is generated, you can run the following commands to see the Angular 6 app running at localhost:4200.

cd crudoperation
ng serve

Angular 6 Project Structure

Routing

Following is our routing configuration. We have configured it to use ListEmpComponent as a default component. Also, do not forget to include it in the main module - app.module.ts.
 
app-routing.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { CommonModule } from '@angular/common';  
  3. import { RouterModule, Routes } from '@angular/router';  
  4. import { ListEmpComponent } from './list-emp/list-emp.component';  
  5. import { AddEmpComponent } from './add-emp/add-emp.component';  
  6.   
  7. export const routes: Routes = [  
  8.   { path: '', component: ListEmpComponent, pathMatch: 'full' },  
  9.   { path: 'list-emp', component: ListEmpComponent },  
  10.   { path: 'add-emp', component: AddEmpComponent }  
  11. ];  
  12.   
  13. @NgModule({  
  14.   imports: [  
  15.     CommonModule,  
  16.     RouterModule.forRoot(routes)  
  17.   ],  
  18.   exports: [RouterModule],  
  19.   declarations: []  
  20. })  
  21. export class AppRoutingModule { }  
app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { HttpClientModule } from '@angular/common/http';  
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import { ReactiveFormsModule } from "@angular/forms";  
  6.   
  7. import { AppComponent } from './app.component';  
  8. import { ListEmpComponent } from './list-emp/list-emp.component';  
  9. import { AddEmpComponent } from './add-emp/add-emp.component';  
  10. import { EmployeeService } from './service/employee.service';  
  11.   
  12. @NgModule({  
  13.   declarations: [  
  14.     AppComponent,  
  15.     ListEmpComponent,  
  16.     AddEmpComponent  
  17.   ],  
  18.   imports: [  
  19.     BrowserModule,  
  20.     HttpClientModule,  
  21.     AppRoutingModule,  
  22.     ReactiveFormsModule  
  23.   ],  
  24.   providers: [EmployeeService],  
  25.   bootstrap: [AppComponent]  
  26. })  
  27. export class AppModule { }  
  28.   
  29. Model  
  30. export class Employee {  
  31.     id?: number;  
  32.     employee_name?: string;  
  33.     employee_salary?: number;  
  34.     employee_age?: number;  
  35. }  
Following is the implementation of our EmployeeService. It has all the API details that are required for the CRUD operation. Here, I have used JSON Server for making API calls. The JSON Server is for front-end developers, which simulates a back-end REST Service to deliver the data in JSON format to the front-end application and make sure everything is working as expected. 
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3. import { Employee } from '../model/employee.model';  
  4.   
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class EmployeeService {  
  9.   
  10.   constructor(private http: HttpClient) { }  
  11.   baseUrl: string = 'http://localhost:3004/posts/';  
  12.   
  13.   getEmployees() {  
  14.     return this.http.get<Employee[]>(this.baseUrl);  
  15.   }  
  16.   deleteEmployees(id: number) {  
  17.     return this.http.delete<Employee[]>(this.baseUrl + id);  
  18.   }  
  19.   createUser(employee: Employee) {  
  20.     return this.http.post(this.baseUrl, employee);  
  21.   }  
  22.   getEmployeeById(id: number) {  
  23.     return this.http.get<Employee>(this.baseUrl + '/' + id);  
  24.   }  
  25.   updateEmployee(employee: Employee) {  
  26.     return this.http.put(this.baseUrl + '/' + employee.id, employee);  
  27.   }  
  28. }  
Creating Components list-emp.component.html
  1. <div class="col-md-12">  
  2.   <h2> User Details</h2>  
  3.   <div class="table-responsive table-container">  
  4.     <table class="table">  
  5.       <thead>  
  6.         <tr>  
  7.           <th>Id</th>  
  8.           <th>Employee Name</th>  
  9.           <th>Salary</th>  
  10.           <th>Age</th>  
  11.         </tr>  
  12.       </thead>  
  13.       <tbody>  
  14.         <tr *ngFor="let emp of employees">  
  15.           <td class="hidden">{{emp.id}}</td>  
  16.           <td>{{emp.employee_name}}</td>  
  17.           <td>{{emp.employee_salary}}</td>  
  18.           <td>{{emp.employee_age}}</td>  
  19.           <td>  
  20.             <button (click)="deleteEmp(emp)" class="btn btn-info"> Delete</button>  
  21.             <button (click)="editEmp(emp)" style="margin-left: 20px;" class="btn btn-info"> Edit</button>  
  22.           </td>  
  23.         </tr>  
  24.       </tbody>  
  25.     </table>  
  26.   </div>  
  27. </div>  
list-emp.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2. import { EmployeeService } from '../service/employee.service';  
  3. import { Employee } from '../model/employee.model';  
  4. import { Router } from "@angular/router";  
  5.   
  6. @Component({  
  7.   selector: 'app-list-emp',  
  8.   templateUrl: './list-emp.component.html',  
  9.   styleUrls: ['./list-emp.component.css']  
  10. })  
  11. export class ListEmpComponent implements OnInit {  
  12.   
  13.   employees: Employee[];  
  14.   
  15.   constructor(private empService: EmployeeService, private router: Router, ) { }  
  16.   
  17.   ngOnInit() {  
  18.     this.empService.getEmployees()  
  19.       .subscribe((data: Employee[]) => {  
  20.         this.employees = data;  
  21.       });  
  22.   }  
  23.   deleteEmp(employee: Employee): void {  
  24.     this.empService.deleteEmployees(employee.id)  
  25.       .subscribe(data => {  
  26.         this.employees = this.employees.filter(u => u !== employee);  
  27.       })  
  28.   }  
  29.   editEmp(employee: Employee): void {  
  30.     localStorage.removeItem('editEmpId');  
  31.     localStorage.setItem('editEmpId', employee.id.toString());  
  32.     this.router.navigate(['add-emp']);  
  33.   }  
  34. }  
add-emp.component.html
  1. <div class="col-md-6">  
  2.   <h2 class="text-center">{{empformlabel}}</h2>  
  3.   <form [formGroup]="addForm" novalidate class="form">  
  4.     <div class="form-group">  
  5.       <label for="empId">Employee Id:</label>  
  6.       <input type="number" formControlName="id" placeholder="Id" name="empId" class="form-control" id="empId">  
  7.     </div>  
  8.   
  9.     <div class="form-group">  
  10.       <label for="empName">Employee Name:</label>  
  11.       <input formControlName="employee_name" placeholder="Employee Name" name="empName" class="form-control" id="empName">  
  12.       <div class="alert  alert-danger" *ngIf="addForm.get('employee_name').hasError('required') && addForm.get('employee_name').touched">  
  13.         Employee Name is required  
  14.       </div>  
  15.     </div>  
  16.   
  17.     <div class="form-group">  
  18.       <label for="empSalary">Employee Salary:</label>  
  19.       <input formControlName="employee_salary" placeholder="Employee Salary" name="employee_salary" class="form-control" id="employee_salary">  
  20.       <div class="alert  alert-danger" *ngIf="addForm.get('employee_salary').hasError('maxlength') && addForm.get('employee_salary').touched">  
  21.         Employee Salary is required and should less than 9 characters.  
  22.       </div>  
  23.     </div>  
  24.   
  25.     <div class="form-group">  
  26.       <label for="empAge">Employee Age:</label>  
  27.       <input formControlName="employee_age" placeholder="Employee Age" name="empAge" class="form-control" id="empAge">  
  28.       <div class="alert  alert-danger" *ngIf=" addForm.get('employee_age').hasError('maxlength') && addForm.get('employee_age').touched">  
  29.         Age is required and should less than 3 characters.  
  30.       </div>  
  31.     </div>  
  32.     <button class="btn btn-success" [disabled]='addForm.invalid' *ngIf="btnvisibility" (click)="onSubmit()">Save</button>  
  33.     <button class="btn btn-success" [disabled]='addForm.invalid' *ngIf="!btnvisibility" (click)="onUpdate()">Update</button>  
  34.   
  35.     <p>Form value: {{ addForm.value | json }}</p>  
  36.   </form>  
  37. </div>  
add-emp.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormBuilder, FormGroup, Validators } from "@angular/forms";  
  3. import { EmployeeService } from '../service/employee.service';  
  4. import { Router } from "@angular/router";  
  5.   
  6. @Component({  
  7.   selector: 'app-add-emp',  
  8.   templateUrl: './add-emp.component.html',  
  9.   styleUrls: ['./add-emp.component.css']  
  10. })  
  11. export class AddEmpComponent implements OnInit {  
  12.   
  13.   empformlabel: string = 'Add Employee';  
  14.   empformbtn: string = 'Save';  
  15.   constructor(private formBuilder: FormBuilder, private router: Router, private empService: EmployeeService) {  
  16.   }  
  17.   
  18.   addForm: FormGroup;  
  19.   btnvisibility: boolean = true;  
  20.   ngOnInit() {  
  21.   
  22.     this.addForm = this.formBuilder.group({  
  23.       id: [],  
  24.       employee_name: ['', Validators.required],  
  25.       employee_salary: ['', [Validators.required, Validators.maxLength(9)]],  
  26.       employee_age: ['', [Validators.required, Validators.maxLength(3)]]  
  27.     });  
  28.   
  29.     let empid = localStorage.getItem('editEmpId');  
  30.     if (+empid > 0) {  
  31.       this.empService.getEmployeeById(+empid).subscribe(data => {  
  32.         this.addForm.patchValue(data);  
  33.       })  
  34.       this.btnvisibility = false;  
  35.       this.empformlabel = 'Edit Employee';  
  36.       this.empformbtn = 'Update';  
  37.     }  
  38.   }  
  39.   onSubmit() {  
  40.     console.log('Create fire');  
  41.     this.empService.createUser(this.addForm.value)  
  42.       .subscribe(data => {  
  43.         this.router.navigate(['list-emp']);  
  44.       },  
  45.       error => {  
  46.         alert(error);  
  47.       });  
  48.   }  
  49.   onUpdate() {  
  50.     console.log('Update fire');  
  51.     this.empService.updateEmployee(this.addForm.value).subscribe(data => {  
  52.       this.router.navigate(['list-emp']);  
  53.     },  
  54.       error => {  
  55.         alert(error);  
  56.       });  
  57.   }  
  58. }  
Global Style style.css

  1. /* You can add global styles to this file, and also import other style files */  
  2. @import "~bootstrap/dist/css/bootstrap.css";  
  3. @import "~font-awesome/css/font-awesome.css";  
  4. .ng-valid[required], .ng-valid.required  {  
  5.   border-left: 5px solid #42A948; /* green */  
  6. }  
  7. .ng-invalid:not(form)  {  
  8.   border-left: 5px solid #a94442; /* red */  
  9. }  
  10. .mtop10{  
  11.   margin-top:10px;  
  12. }  

Testing Angular 6 Application

Now, run the command ng serve and hit localhost:4200.

You can see the following screen with a list of users. On this page, you can perform actions to add, edit, and delete an employee. 

Testing Angular 6 Application

Testing Angular 6 Application
 
Testing Angular 6 Application

Here, we have used the same component to Add and Edit/Update the Employee.

Conclusion

In this article, we learned about Angular 6 CRUD operations and created a demo application. The source can be downloaded from GitHub here.


Similar Articles