Angular CRUD operation Example

Angular CRUD operation Example

In this article, we’ll see how to implement CRUD operation in Angular. When you want to learn anything the good approach would be to learn CRUD operation. so we will see Angular CRUD(Create, Read, Update, Delete) operation with Bootstrap.

In this article we will see Angular CRUD example for Employee Management.


CRUD Operations In Angular Application


1) Create Angular application

Run the following command to create new project in Angular


new new angular-crud-example
cd angular-crud-example

Open this project in your favorite editor or VS code editor.


2) Install Bootstrap

This is optional step. but for styling you can install bootstrap which is awesome css framework.

so in this angular crud operation we will see example with bootstrap.


npm install bootstrap

Now let’s import bootstrap.css in style.css file

src/style.css


@import "~bootstrap/dist/css/bootstrap.css";

3) Create Angular Module

Now we will create employee module and we will create all create, read, edit, delete components in this module.

Generate angular module using the following command:


ng generate module employee --routing

It will create module file and routing file as shown in belows:

src/app/employee/employee.module.ts
src/app/employee/employee-routing.module.ts

4) Create Angular Component for Module

Now we will create all create, read, edit, delete components for Angular CRUD operation in EmployeeModule.

Run the following command to generate all components:


ng generate component employee/list
ng generate component employee/view
ng generate component employee/create
ng generate component employee/edit

If you will run the above command it will run all components with specific folder for it.


5) Create Routing to Setup Angular CRUD

Now we will configure routing to navigate to Create, Edit, Delete, List page.

src/app/employee/employee-routing.module.ts


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ListComponent } from './list/list.component';
import { ViewComponent } from './view/view.component';
import { CreateComponent } from './create/create.component';
import { EditComponent } from './edit/edit.component';
  
const routes: Routes = [
  { path: 'employee', redirectTo: 'employee/list', pathMatch: 'full'},
  { path: 'employee/list', component: ListComponent },
  { path: 'employee/:employeeId/view', component: ViewComponent },
  { path: 'employee/create', component: CreateComponent },
  { path: 'employee/:employeeId/edit', component: EditComponent } 
];
  
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class EmployeeRoutingModule { }

6) Create Interface for Angular CRUD

Now we will create interface for employee entity using the following command

ng generate interface employee/employee

src/app/employee/employee.ts


export interface Employee {   
  id: number;    
  firstName: string;    
  lastName: string;
}

7) Create Angular Service to perform Angular CRUD operation

Now we will create service to perform all crud operation but simplicity we are not going create actual server but we will use fake rest api using JSONPlaceholder

Now create service in angular using following command

ng generate service employee/employee

src/app/employee/employee.service.ts


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
   
import {  Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
    
import { Employee} from './employee';
     
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
     
  private apiURL = "https://jsonplaceholder.typicode.com";
     
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  }
   
  constructor(private httpClient: HttpClient) { }
     
  getAll(): Observable {
    return this.httpClient.get(this.apiURL + '/employees/')
    .pipe(
      catchError(this.errorHandler)
    )
  }
     
  create(employee:Employee): Observable {
    return this.httpClient.post(this.apiURL + '/employees/', JSON.stringify(post), this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }  
     
  find(id:number): Observable {
    return this.httpClient.get(this.apiURL + '/empoyees/' + id)
    .pipe(
      catchError(this.errorHandler)
    )
  }
     
  update(id:number, post:Post): Observable {
    return this.httpClient.put(this.apiURL + '/employees/' + id, JSON.stringify(post), this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }
     
  delete(id:number){
    return this.httpClient.delete(this.apiURL + '/employees/' + id, this.httpOptions)
    .pipe(
      catchError(this.errorHandler)
    )
  }
    
    
  errorHandler(error:any) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    return throwError(errorMessage);
 }
}

8) Update Angular CRUD component

Now we will update all component to show list or form to add/update data.

1) List Component

src/app/employee/list/list.component.ts


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';
import { Employee } from '../employee';
    
@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
     
  employees: Employee[] = [];
   
  constructor(public employeeService: EmployeeService) { }
    
  ngOnInit(): void {
    this.employeeService.getAll().subscribe((data: Employee[])=>{
      this.employees= data;
    })  
  }
    
  deleteEmployee(id:number){
    this.employeeService.delete(id).subscribe(res => {
         this.employees = this.employees.filter(item => item.id !== id);
    })
  }
  
}

src/app/employee/list/list.component.html


<div class="container">
    <h1>Angular CRUD Example</h1>
  
    <a href="#" routerLink="/employee/create/" class="btn btn-success">Create New Employee</a>
    
    <table class="table table-bordered">
      <tr>
        <th>ID</th>
        <th>FirstName</th>
        <th>LastName</th>
        <th width="220px">Action</th>
      </tr>
      <tr *ngFor="let employee of employees">
        <td>{{ employee.id }}</td>
        <td>{{ employee.firstName}}</td>
        <td>{{ employee.lastName}}</td>
        <td>
          <a href="#" [routerLink]="['/employee/', employee.id, 'view']" class="btn btn-info">View</a>
          <a href="#" [routerLink]="['/employee/', employee.id, 'edit']" class="btn btn-primary">Edit</a>
          <button type="button" (click)="deleteEmployee(employee.id)" class="btn btn-danger">Delete</button>
        </td>
      </tr>
    </table>
 </div>

2) Create Page component

Now we will see how to insert data using Angular reactive form for Angular CRUD example.

src/app/employee/create/create.component.ts


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';
import { Router } from '@angular/router';
import { FormGroup, FormControl, Validators} from '@angular/forms';
   
@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
  
  form: FormGroup;
   
  constructor(
    public employeeService: EmployeeService,
    private router: Router
  ) { }
  
  ngOnInit(): void {
    this.form = new FormGroup({
      firstName: new FormControl('', [Validators.required]),
      lastName: new FormControl('', Validators.required)
    });
  }
   
  get f(){
    return this.form.controls;
  }
    
  submit(){
    this.employeeService.create(this.form.value).subscribe(res => {
         this.router.navigateByUrl('employee/list');
    })
  }
  
}

src/app/employee/create/create.component.html


<div class="container">
    <h1>Create New Employee</h1>
  
    <a href="#" routerlink="/employee/list" class="btn btn-primary">Back</a>
        
    <form [formgroup]="form" (ngsubmit)="submit()">
  
        <div class="form-group">
            <label for="title">First Name:</label>
            <input formcontrolname="firstName" id="firstName" type="text" class="form-control">
            <div *ngif="f.firstName.touched && f.firstName.invalid" class="alert alert-danger">
                <div *ngif="f.firstName.errors?.required">First Name is required.</div>
            </div>
        </div>
  
        <div class="form-group">
            <label for="title">Last Name:</label>
            <input formcontrolname="lastName" id="lastName" type="text" class="form-control">
            <div *ngif="f.lastName.touched && f.lastName.invalid" class="alert alert-danger">
                <div *ngif="f.lastName.errors?.required">Last Name is required.</div>
            </div>
        </div>
  
        <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>
    </form>
</div>

3) Edit Page component

Now we will see edit page component for Angular CRUD example.

src/app/employee/edit/edit.component.ts


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Employee} from '../employee';
import { FormGroup, FormControl, Validators} from '@angular/forms';
   
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
    
  id: number;
  employee: Employee;
  form: FormGroup;
  
  constructor(
    public employeeService: EmployeeService,
    private route: ActivatedRoute,
    private router: Router
  ) { }
  
  ngOnInit(): void {
    this.id = this.route.snapshot.params['employeeId'];
    this.employeeService.find(this.id).subscribe((data: Employee)=>{
      this.employees = data;
    });
    
    this.form = new FormGroup({
      firstName: new FormControl('', [Validators.required]),
      lastName: new FormControl('', Validators.required)
    });
  }
   
  get f(){
    return this.form.controls;
  }
     
  submit(){
    this.employeeService.update(this.id, this.form.value).subscribe(res => {
         this.router.navigateByUrl('employee/list');
    })
  }
   
}

src/app/employee/edit/edit.component.html


<div class="container">
    <h1>Update Employee</h1>
  
    <a href="#" routerlink="/post/index" class="btn btn-primary">Back</a>
        
    <form [formgroup]="form" (ngsubmit)="submit()">
  
        <div class="form-group">
            <label for="title">FirstName:</label>
            <input formcontrolname="firstName" id="firstName" type="text" [(ngmodel)]="employee.firstName" class="form-control">
            <div *ngif="f.firstName.touched && f.firstName.invalid" class="alert alert-danger">
                <div *ngif="f.firstName.errors?.required">FirstName is required.</div>
            </div>
        </div>
         
        <div class="form-group">
            <label for="title">LastName:</label>
            <input formcontrolname="lastName" id="lastName" type="text" [(ngmodel)]="employee.lastName" class="form-control">
            <div *ngif="f.lastName.touched && f.lastName.invalid" class="alert alert-danger">
                <div *ngif="f.lastName.errors?.required">LastName is required.</div>
            </div>
        </div>
        
        <button class="btn btn-primary" type="submit" [disabled]="!form.valid">Update</button>
    </form>
</div>

4) Detail Page Component

Now we will see detail page component for Angular CRUD example

src/app/employee/view/view.component.ts


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from '../employee.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Employee } from '../employee';
  
@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {
   
  id: number;
  employee: Employee;
   
  constructor(
    public employeeService: EmployeeService,
    private route: ActivatedRoute,
    private router: Router
   ) { }
  
  ngOnInit(): void {
    this.id = this.route.snapshot.params['employeeId'];
      
    this.employeeService.find(this.id).subscribe((data: Employee)=>{
      this.employee = data;
    });
  }
  
}

<div class="container">
    <h1>View Post</h1>
  
    <a href="#" routerlink="/post/index" class="btn btn-primary">Back</a>
   
    <div>
        <strong>ID:</strong>
        <p>{{ post.id }}</p>
    </div>
   
    <div>
        <strong>First Name:</strong>
        <p>{{ employee.firstName }}</p>
    </div>
   
    <div>
        <strong>Last Name:</strong>
        <p>{{ employee.lastName }}</p>
    </div>
   
</div>

Now open app.component.html and update it

src/app/app.component.html


<router-outlet></router-outlet>

9) Import HttpClientModule in app.module.ts

src/app/app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
  
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
  
import { EmployeeModule } from './employee/employee.module';
  
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    EmployeeModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

src/app/post/post.module.ts


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
  
import { EmployeeRoutingModule } from './employee-routing.module';
import { ListComponent } from './list/list.component';
import { ViewComponent } from './view/view.component';
import { CreateComponent } from './create/create.component';
import { EditComponent } from './edit/edit.component';
  
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
  
@NgModule({
  declarations: [ListComponent, ViewComponent, CreateComponent, EditComponent],
  imports: [
    CommonModule,
    EmployeeRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ]
})
export class EmployeeModule { }

Now we are done with Angular CRUD example with bootstrap. Now you can run the Angular CRUD project using the ng serve command. so in this article we have see How to Perform CRUD Operations using Angular.

I hope you like this Angular CRUD operation Example article.


Also Read