Skip to main content

Angular(16) CRUD Example | Search | Sorting | Pagination

In this article, we will implement an Angular(16) CRUD sample.

Angular:

Angular is a front-end framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean.
  • Angular components compose of 3 files like TypeScript(*.ts), HTML File(*.html), CSS File(*.css)
  • Components typescript file and HTML file support 2-way binding which means data flow is bi-directional.
  • The component typescript file listens for all HTML events from the HTML file.

Create Angular(16) Application:

Let's create the angular(16) application to accomplish our demo.

Now install the angular CLI command on our local machine. If your system already installed angular CLI to get the latest angular application just run the following command again so that angular CLI gets updated.
npm install -g @angular/cli

Run the below command to create an angular application.
ng new project_name

While creating the app CLI requires few inputs from us
  • Add the angular routing
  • Choose the 'CSS' styles sheet
Let's explore the few default files in the angular project.
  • package.json - contains commands like build, run, test,etc. It also contains packages or library references that our angular application requires.
  • angular.json - contains setup and configuration of angular.
  • src/index.html - only HTML file of the angular application it contains the root angular component element like 'app-root' the area for the component to render.
  • src/main.ts - entry file of our angular application to execute.
  • src/app/app.module.ts - entry module.
  • src/app/app-routing.modulet.ts - entry route module.
  • app(folder or root component folder) - contains root component like 'AppComponent' that consist of files like 'app.component.ts', 'app.component.html', 'app.component.css'.

Install Angular Material Library:

Let's install the angular material library in our application.
ng add @angular/material

While installing library we have to give some inputs like:
  • Would you like to proceed to install angular material library - click 'y'(yes)
  • Choose default theme
  • Choose angular default typography
  • Choose angular material animations

Toolbar Material Component To Create Menu:

Let's use the angular material toolbar component to create a menu for our sample. So let's replace the HTML content in 'app.component.html'.
src/app/app.component.html:
<mat-toolbar color="primary">
  <span>Super Heroes</span>
</mat-toolbar>
<router-outlet></router-outlet>
  • (Line: 1-3) Rendered our angular material toolbar component element.
  • (Line: 5) The 'router-outlet' angular component element here routed component or page-level components get rendered.
Import 'MatToolbarModule' in the 'AppModule'.
src/app/app.appmodule.ts:
import {MatToolbarModule} from '@angular/material/toolbar';
// code hidden for display purpose
@NgModule({
  imports: [
    MatToolbarModule
  ]
})
export class AppModule { }

Setup Json Server:

Let's set up a fake API by setting up the JSON server in our local machine.

Run the below command to install the JSON server globally onto our local system
npm install -g json-server

Now go to our angular application and add a command to run the JSON server into the 'package.json' file.
"json-run":"json-server --watch db.json"

Now to invoke the above command, run the below command in the angular application root folder.
npm run json-run
After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data into the file as below.

Now let's access the endpoint as 'http://localhost:3000/superHeroes'

Create Angular Component 'AllSuperHeroesComponent':

Let's create a new angular component like 'AllSuperHeroesComponent'.
ng generate component super-heroes/all-superheroes --skip-tests


Configure the 'AllSuperHeroesComponent' route in 'AppRoutingModule'
src/app/app-routing.module.ts:
import { AllSuperheroesComponent } from './super-heroes/all-superheroes/all-superheroes.component';
// existing code hidden for display purpose
const routes: Routes = [{
  path:'',
  component: AllSuperheroesComponent
}];
  • Here empty path represents that is the home URL and is mapped to our 'AllSuperHeroesComponent'

Create API Response Model 'SuperHeroes':

Let's create an API response model like 'SuperHeroes'.
ng generate interface super-heroes/super-heroes

src/app/super-heroes/super-heroes.ts:
export interface SuperHeroes {
  id: number;
  name: string;
  imageUrl: string;
  franchise: string;
  gender: string;
}

Create Angular Service 'SuperHeroesService':

Let's create an angular service like 'SuperHeroesService', where we are going to write our API calls logic.
ng generate service super-heroes/super-heroes --skip-tests


Now inject the 'HttpClient' instance into the service constructor. The 'HttpClient' provides in-built methods for invoking the API calls.
src/app/super-heroes/super-heroes.service.ts:
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http'
@Injectable({
  providedIn: 'root'
})
export class SuperHeroesService {
  constructor(private http:HttpClient) { }
}
Now import 'HttpClientModule' in 'AppModule'.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http';
// existing code hidden for display purpose
@NgModule({
  imports: [
    HttpClientModule
  ]
})
export class AppModule { }

Implement Read Operation:

Let's implement the 'Read' operation by invoking the HTTP GET endpoint and then binding the API response to UI.

In the 'SuperHeroesService' let's implement the logic to call HTTP GET endpoint.
src/super-heroes/super-heroes.service.ts:
get(): Observable<SuperHeroes[]> {
  return this.http.get<SuperHeroes[]>('http://localhost:3000/superHeroes');
}
Let's add the CSS styles into the 'all-superheroes.component.css' file.
src/app/super-heroes/all-superheroes/all-superheroes.component.css:
.example-card {
  max-width: 250px;
  margin: 10px;
  background-color: white;
}
.app-container {
  justify-content: center;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
Let's add the following logic in to the 'all-superheroes.component.ts' file
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-all-superheroes',
  templateUrl: './all-superheroes.component.html',
  styleUrls: ['./all-superheroes.component.css'],
})
export class AllSuperheroesComponent implements OnInit {
  allSuperHeroes: SuperHeroes[] = [];
  constructor(private superHeroesService: SuperHeroesService) {}
  ngOnInit(): void {
    this.getApi();
  }
  getApi() {
    this.superHeroesService.get().subscribe((response) => {
      this.allSuperHeroes = response;
    });
  }
}
  • (Line: 5-10) To make our 'AllSuperHeroesComponent' an angular component we have to decorate our class with '@Component' attribute that loads from the '@angular/core'. The 'selector' property defines the component HTML element tag. The 'templateUrl' property links the component HTML file.
  • (Line: 11) The 'allSuperHeroes' variable to store the API response.
  • (Line: 12) Injected our 'SuperHeroesService'.
  • (Line: 16-20) Invoking the GET API call and API response stored to the 'allSuperHeroes' variable.
  • (Line: 13-15) The 'ngOnInit' is an angular life cycle method that executes on component renders. So in this method, we invoke our 'getAPI' method.
Let's add the HTML into the 'all-superheroes.compnent.html'
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
<div class="app-container">
  <mat-card class="example-card" *ngFor="let item of allSuperHeroes">
    <mat-card-header>
      <div mat-card-avatar class="example-header-image"></div>
      <mat-card-title >{{ item.name }}</mat-card-title>
      <button
        mat-mini-fab
        matTooltip="Primary"
        color="primary"
        aria-label="Example mini fab with a heart icon"
      >
        {{ item.id }}
      </button>
    </mat-card-header>
    <img mat-card-image src="{{ item.imageUrl }}" alt="" />
    <mat-card-content>
      <p>Franchise - {{ item.franchise }}</p>
      <p>Gender - {{ item.gender }}</p>
    </mat-card-content>
  </mat-card>
</div>
  • Here we are using an angular material card design to display the items.
  • (Line: 2) Using the 'ngFor' directive looping the items.
  • In angular for binding the data we use '{{}}'.
Now import the required angular material component into 'AppModule'.
src/app/app.module.ts:
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
// existing code hidden for display purpose
@NgModule({
  imports: [
    MatButtonModule,
    MatCardModule,
  ]
})
export class AppModule {}

Create Angular Component 'AddSuperHeroesComponent':

Let's create a new angular component like 'AddSuperHeroesComponent'
ng generate component super-heroes/add-superheroes --skip-tests


Let's configure 'AddSuperHeroesComponent' route in 'AppRouteMoudle'.
src/app/app-routing.module.ts:
import { AddSuperheroesComponent } from './super-heroes/add-superheroes/add-superheroes.component';
// existing code hidden for display purpose
const routes: Routes = [{
  path:'add',
  component: AddSuperheroesComponent
}];

Implement Create Operation:

Let's implement the 'Create' operation by invoking the HTTP POST API call to create an item in the 'SuperHeroesService'.
src/app/super-heroes/super-heroes.service.ts:
add(payload:SuperHeroes){
  return this.http.post('http://localhost:3000/superHeroes', payload);
}
  • The 'HttpClient.post()' method invokes the HTTP Post endpoint to create an item.
Let's add the following logic into the 'add-superheroes.component.ts'.
src/app/super-heroes/add-superheroes/add-superheroes.component.ts:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-add-superheroes',
  templateUrl: './add-superheroes.component.html',
  styleUrls: ['./add-superheroes.component.css'],
})
export class AddSuperheroesComponent {
  constructor(
    private fb: FormBuilder,
    private superHeroService: SuperHeroesService,
    private router: Router
  ) {}

  addSuperHeroForm = this.fb.group({
    name: [''],
    imageUrl: [''],
    franchise: [''],
    gender: [''],
  });
  noImage =
    'add-preview-image.png';
  create() {
    this.superHeroService
      .add(this.addSuperHeroForm.value as SuperHeroes)
      .subscribe(() => {
        this.router.navigate(['/']);
      });
  }
}
  • (Line: 14) Injected the 'FormBuilder' that loads from the '@angular/form'
  • (Line: 15) Injected the 'SuperHeroService'
  • (Line: 16) Injected the 'Router' service that loads from the '@angular/router'
  • (Line: 19-24) The 'addSuperHeroForm' variable is assigned with the 'FormBuilder.group()'. Here we need to define all the form field variables with initial values.
  • (Line: 25) Here 'noImage' variable to store the sample preview image.
  • (Line: 27-33) The 'create()' method contains logic to invoke the HTTP Post.
Let's add a few styles in 'add-superheroes.component.css'.
src/app/super-heroes/add-superheroes/add-superheroes.component.css:
.card {
  width: 800px;
}
.card-container {
  display: flex;
  justify-content: center;
  margin-top: 14px;
  column-gap: 2em;
}
.form-container {
  display: flex;
  flex-direction: column;
}

.heading{
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 14px;
}
Let's add the following HTML 'add-superheroes.component.html'.
src/app/super-heroes/add-superheroes/add-superheroes.component.html:
<div class="heading">
  <mat-chip color="primary"> Create A New Super Hereo </mat-chip>
</div>
<div class="card-container">
  <mat-card class="card">
    <div class="card-container">
      <form
        class="form-container"
        [formGroup]="addSuperHeroForm"
        (ngSubmit)="create()"
      >
        <mat-form-field appearance="outline" style="width: 400px">
          <mat-label>Name</mat-label>
          <input matInput formControlName="name" />
        </mat-form-field>
        <mat-form-field appearance="outline" style="width: 400px">
          <mat-label>Image URL</mat-label>
          <input matInput formControlName="imageUrl" />
        </mat-form-field>
        <mat-form-field appearance="outline" style="width: 400px">
          <mat-label>Franchise</mat-label>
          <mat-select formControlName="franchise">
            <mat-option value="marvel">Marvel</mat-option>
            <mat-option value="dc">DC</mat-option>
          </mat-select>
        </mat-form-field>
        <mat-radio-group aria-label="Select an option" formControlName="gender">
          <mat-radio-button value="male">Male</mat-radio-button>
          <mat-radio-button value="female">Female</mat-radio-button>
        </mat-radio-group>
        <button mat-raised-button color="primary" style="margin: 10px 0px">
          Add
        </button>
      </form>
      <div>
        <div>
          <img
            mat-card-lg-image
            src="{{
              this.addSuperHeroForm.get('imageUrl')?.value
                ? this.addSuperHeroForm.get('imageUrl')?.value
                : noImage
            }}"
          />
        </div>
      </div>
    </div>
  </mat-card>
</div>
  • (Line: 9) Here [formGroup] attribute is assigned with our form variable like 'addSuperHeroForm'.
  • (Line: 10) Here registered 'ngSubmit' event that gets fired on form submission. Here are form submit event is registered with the 'create()' method.
  • Here each input field with registered with the 'formControlName' and its values should be the property name of the 'addSuperHeroForm'.
  • (Line: 37- 44) Here conditionally display the image URL preview.
Add the following angular material modules and 'ReactiveFormsModule' in the 'AppModule'.
src/app/app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {MatFormFieldModule} from '@angular/material/form-field';
import {MatChipsModule} from '@angular/material/chips';
import {MatInputModule} from '@angular/material/input';
import {MatSelectModule} from '@angular/material/select';
import {MatRadioModule} from '@angular/material/radio';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { AllSuperheroesComponent } from './super-heroes/all-superheroes/all-superheroes.component';
import { HttpClientModule } from '@angular/common/http';
import { AddSuperheroesComponent } from './super-heroes/add-superheroes/add-superheroes.component';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent, AllSuperheroesComponent, AddSuperheroesComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    HttpClientModule,
    MatButtonModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatChipsModule,
    MatSelectModule,
    MatRadioModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}
Navigate from the 'AllSuperHeroesComponent' to 'AddSuperHeroesComponent', let's add the anchor link button in 'AllSuperHeroesComponent'.
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
<div class="app-container" style="margin-top: 5px;">
  <a mat-raised-button color="primary" routerLink="/add">Add</a>
</div>
(Step 1)

(Step 2)

Create Angular Component 'EditSuperHeroesComponent':

Let's create a new angular component like 'EditSuperHeroesComponent'.
ng generate component super-heroes/edit-superheroes --skip-tests


Now configure the route for 'EditSuperHeroesComponent' in 'AppRoutingModule'.
src/app/app-routing.module.ts:
import { EditSuperheroesComponent } from './super-heroes/edit-superheroes/edit-superheroes.component';
// existing code hidden for display purpose
const routes: Routes = [
  {
    path: 'edit/:id',
    component: EditSuperheroesComponent
  }
];

Implement Update Operation:

Let's implement the 'Update' operation by invoking the HTTP PUT API endpoint.

In the 'SuperHereosService' let's integrate API calls like HTTP GET by id and HTTP PUT endpoints.
src/app/super-heroes/super-heroes.service.ts:
getById(id: number): Observable<SuperHeroes> {
	return this.http.get<SuperHeroes>(
	  `http://localhost:3000/superHeroes/${id}`
	);
}

update(payload: SuperHeroes): Observable<SuperHeroes> {
	return this.http.put<SuperHeroes>(
	  `http://localhost:3000/superHeroes/${payload.id}`,
	  payload
	);
}
  • (Line: 1-5) Here invoking the HTTP GET Endpoint by 'id' value which is the item to be edited.
  • (Line: 7-12) The 'HttpClient.put()' method invokes updating the item.
Let's add the following styles in 'edit-superheroes.component.css'.
src/app/super-heroes/edit-superheroes/edit-superheroes.component.css:
.card {
    width: 800px;
  }
  .card-container {
    display: flex;
    justify-content: center;
    margin-top: 14px;
    column-gap: 2em;
  }
  .form-container {
    display: flex;
    flex-direction: column;
  }
  
  .heading{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 14px;
}
Let's add the following logic in 'edit-superheroes.component.ts'.
src/app/super-heroes/edit-superheroes/edit-superheroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-edit-superheroes',
  templateUrl: './edit-superheroes.component.html',
  styleUrls: ['./edit-superheroes.component.css'],
})
export class EditSuperheroesComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private superHeroeService: SuperHeroesService,
    private route: ActivatedRoute,
    private router: Router
  ) {}
  ngOnInit(): void {
    this.route.paramMap.subscribe((param) => {
      var id = Number(param.get('id'));
      this.getById(id);
    });
  }

  noImage =
    'previewImages.png';

  updateSuperHeroForm = this.fb.group({
    id: [0],
    name: [''],
    imageUrl: [''],
    franchise: [''],
    gender: [''],
  });

  getById(id: number) {
    this.superHeroeService.getById(id).subscribe((data) => {
      this.updateSuperHeroForm.setValue(data);
    });
  }

  update() {
    this.superHeroeService.update((this.updateSuperHeroForm.value as SuperHeroes))
    .subscribe(() => {
      this.router.navigate(["/"]);
    })
  }
}
  • (Line: 14) Injected the 'FormBuilder' that loads from the '@angular/forms'.
  • (Line: 15) Injected the 'SuperHeroesService'.
  • (Line: 16) Injected the 'ActivatedRoute' that loads from the '@angular/router'.
  • (Line: 17) Injected the 'Router' that loads from the '@angular/router'.
  • (Line: 20-23) Here reading the item id from the URL.
  • (Line: 29-35) Declared reactive form variable like 'updateSuperHeroForm'.
  • (Line: 37-41) Invoking the HTTP GET by id API endpoint.
  • (Line: 43-48) Invoking the HTTP PUT endpoint to update the record.
Add the HTML content into the 'edit-superheroes.component.html'.
src/app/super-heroes/edit-superheroes.component.html:
<div class="heading">
  <mat-chip color="primary"> Update Super Hereo </mat-chip>
</div>
<div class="card-container">
  <mat-card class="card">
    <div class="card-container">
      <form
        class="form-container"
        [formGroup]="updateSuperHeroForm"
        (ngSubmit)="update()"
      >
        <mat-form-field appearance="outline" style="width: 400px">
          <mat-label>Name</mat-label>
          <input matInput formControlName="name" />
        </mat-form-field>
        <mat-form-field appearance="outline" style="width: 400px">
          <mat-label>Image URL</mat-label>
          <input matInput formControlName="imageUrl" />
        </mat-form-field>
        <mat-form-field appearance="outline" style="width: 400px">
          <mat-label>Franchise</mat-label>
          <mat-select formControlName="franchise">
            <mat-option value="marvel">Marvel</mat-option>
            <mat-option value="dc">DC</mat-option>
          </mat-select>
        </mat-form-field>
        <mat-radio-group aria-label="Select an option" formControlName="gender">
          <mat-radio-button value="male">Male</mat-radio-button>
          <mat-radio-button value="female">Female</mat-radio-button>
        </mat-radio-group>
        <button mat-raised-button color="primary" style="margin: 10px 0px">
          Update
        </button>
      </form>
      <div>
        <div>
          <img
            mat-card-lg-image
            src="{{
              this.updateSuperHeroForm.get('imageUrl')?.value
                ? this.updateSuperHeroForm.get('imageUrl')?.value
                : noImage
            }}"
          />
        </div>
      </div>
    </div>
  </mat-card>
</div>
Now configure the 'Edit' button on each item on the 'all-superheroes.component.html'.
src/app/super-heroes/all-superheroes/all-superheroes.component.html:
<mat-card-actions>
  <a mat-raised-button color="primary" [routerLink]="['/edit', item.id]">Edit</a>
</mat-card-actions>
(Step 1)
(Step 2)

Create Angular Component 'DeleteDialogSuperHeroComponent':

Let's create a new angular component like 'DeleteDialogSuperHeroComponent'.
ng generate component super-heroes/delete-dialog-superheroes --skip-tests

Implement Delete Operation:

Let's implement the 'Delete' operation by invoking the Http Delete API endpoint.

In the 'SuperHeroesService' let's add the logic to call the Delete API endpoint.
src/app/super-heroes/super-heroes.service.ts:
delete(id: number) {
  return this.http.delete(`http://localhost:3000/superHeroes/${id}`);
}
Let's add the following logic in 'delete-dialog-superheroes.component.ts'
src/app/super-heroes/delete-dialog-superheroes/delete-diaog-superheroes.component.ts:
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-delete-dialog-superheroes',
  templateUrl: './delete-dialog-superheroes.component.html',
  styleUrls: ['./delete-dialog-superheroes.component.css'],
})
export class DeleteDialogSuperheroesComponent {
  constructor(
    public dialogRef: MatDialogRef<DeleteDialogSuperheroesComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    private superHeroesService: SuperHeroesService
  ) {}

  confirmDelete() {
    this.superHeroesService.delete(this.data.id).subscribe(() => {
      this.dialogRef.close(this.data.id);
    });
  }
}
  • (Line: 12) The 'MatDialogRef' loads from the '@angular/material/dilog'. The 'MatDialogRef' gives control over the dialog box inside of it.
  • (Line: 13) The 'MAT_DIALOG_DATA' token reads the data from the parent component that invokes our dialog.
  • (Line: 14) Injected our 'SuperHeroesService'
  • (Line: 17-21) The 'confirmDelete' method invokes the HTTP DELETE API call. After API call completes we will close the dialog by using 'dialogRef.close()' method.
Let's add the following HTML into 'delete-dialog-superheroes.component.html'.
src/app/super-heroes/delete-dialog-superheroes/delete-diaog-superheroes.component.ts:
<h1 mat-dialog-title>Delete file</h1>
<div mat-dialog-content>
  Would you like to delete ?
</div>
<div mat-dialog-actions>
  <button mat-button mat-dialog-close>No</button>
  <button mat-button (click)="confirmDelete()" cdkFocusInitial>Confirm Delete</button>
</div>
  • (Line: 7) Here registered with 'confirmDelete()' method.
Now register the 'MatDialogModule' in the 'AppModule'.
src/app/app.module.ts:
import {MatDialogModule} from '@angular/material/dialog';
// existing code hidden for display purpose
@NgModule({
  imports: [
    MatDialogModule
  ]
})
export class AppModule {}

Let's add the delete logic in 'all-super-heroes.component.ts'
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-all-superheroes',
  templateUrl: './all-superheroes.component.html',
  styleUrls: ['./all-superheroes.component.css'],
})
export class AllSuperheroesComponent implements OnInit {
  allSuperHeroes: SuperHeroes[] = [];

  constructor(
    private superHeroesService: SuperHeroesService,
    public dialog: MatDialog
  ) {}
  ngOnInit(): void {
    this.getApi();
  }

  getApi() {
    this.superHeroesService.get().subscribe((response) => {
      this.allSuperHeroes = response;
    });
  }

  deleteItem(id: number) {
    const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
      width: '250px',
      data: { id },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.allSuperHeroes = this.allSuperHeroes.filter((_) => _.id !== id);
      }
    });
  }
}
  • (Line: 17) Inject the 'MatDialog' that loads from the '@angular/material/dialog'.
  • (Line: 30-33) Open the material dialog box and also we pass the item 'id' value that needs to be deleted.
  • (Line: 35-39) The 'afterClosed()' method executes after closing the material dialog.
Let's add the 'Delete' button in 'all-superheroes.component.html'
src/app/super-heroes/all-superheroes/all-superheroes.component.html:
<button mat-raised-button color="warn" (click)="deleteItem(item.id)">Delete</button>

Implement Sorting:

Let's change the HTTP GET API call in the 'SuperHeroService'.
src/app/super-heroes/super-heroes.service.ts:
get(sortColumn: string, sortType: string): Observable<SuperHeroes[]> {
	let url = "http://localhost:3000/superHeroes?"
	if(sortColumn && sortType){
	  url = `${url}_sort=${sortColumn}&_order=${sortType}`
	}
	return this.http.get<SuperHeroes[]>(url);
}
  • Here we are adding query parameters like '_sort' and '_order' to our endpoint.
Let's update the logic in the 'all-superheroes.component.ts'.
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-all-superheroes',
  templateUrl: './all-superheroes.component.html',
  styleUrls: ['./all-superheroes.component.css'],
})
export class AllSuperheroesComponent implements OnInit {
  sortingControl = new FormControl('');
  allSuperHeroes: SuperHeroes[] = [];

  constructor(
    private superHeroesService: SuperHeroesService,
    public dialog: MatDialog
  ) {}
  ngOnInit(): void {
    this.getApi('', '');
    this.sortingControl.valueChanges.subscribe((value) => {
      if (value) {
        this.doSorting(value);
      }
    });
  }

  doSorting(value: string) {
    let sortColumn: string = '';
    let sortType: string = '';
    if (value.toLowerCase() === 'id-by-desc') {
      sortColumn = 'id';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'id-by-asc') {
      sortColumn = 'id';
      sortType = 'asc';
    } else if (value.toLowerCase() === 'franchise-by-desc') {
      sortColumn = 'franchise';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'franchise-by-asc') {
      sortColumn = 'franchise';
      sortType = 'asc';
    } else if (value.toLowerCase() === 'gender-by-desc') {
      sortColumn = 'gender';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'gender-by-asc') {
      sortColumn = 'gender';
      sortType = 'asc';
    }
    this.getApi(sortColumn, sortType);
  }

  getApi(sortColumn: string, sortType: string) {
    this.superHeroesService.get(sortColumn, sortType).subscribe((response) => {
      this.allSuperHeroes = response;
    });
  }

  deleteItem(id: number) {
    const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
      width: '250px',
      data: { id },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.allSuperHeroes = this.allSuperHeroes.filter((_) => _.id !== id);
      }
    });
  }
}
  • (Line: 14) Declared 'sortingControl' variable of type 'FormControl'.
  • (Line: 23-27) Here listening to the 'sortingControl' value change.
  • (Line: 30-53)In 'doSorting()' method we are preparing the 'sortColumn' and 'sortType' values.
Let's add the HTML in the 'all-superheroes.component.html:
src/app/super-heroes/all-superheroes/all-superheroes.component.html:
<div class="filter-container">
  <mat-form-field appearance="fill" >
    <mat-label> -Sorting- </mat-label>
    <mat-select [formControl]="sortingControl">
      <mat-option value="">-select-</mat-option>
      <mat-option value="id-by-desc">Id By Desc</mat-option>
      <mat-option value="id-by-asc">Id By Asc</mat-option>
      <mat-option value="franchise-by-desc">Franchise By Desc</mat-option>
      <mat-option value="franchise-by-asc">Franchise By Asc</mat-option>
      <mat-option value="gender-by-desc">Gender By Desc</mat-option>
      <mat-option value="gender-by-asc">Gender By Asc</mat-option>
    </mat-select>
  </mat-form-field>
</div>
  • Here we rendered our sorting dropdown
Let's add the CSS in the 'all-superheroes.component.css:
src/app/super-heroes/all-superheroes/all-superheroes.component.css:
.filter-container{
  display: flex;
  margin: 15px;
}

Implement Search Operation:

Let's implement the search operation. So let's update the HTTP GET API call.
src/app/super-heroes/super-heroes.service.ts:
get(
sortColumn: string,
sortType: string,
searchKey: string
): Observable<SuperHeroes[]> {
let url = 'http://localhost:3000/superHeroes?';
if (sortColumn && sortType) {
  url = `${url}_sort=${sortColumn}&_order=${sortType}`;
}

if (searchKey) {
  if (url.indexOf('&') > -1) {
	url = `${url}&q=${searchKey}`;
  } else {
	url = `${url}q=${searchKey}`;
  }
}
return this.http.get<SuperHeroes[]>(url);
}
  • (Line: 11-17) Our JSON server supports text search by using the 'q' query parameter.
Let's update the logic in 'all-superheroes.component.ts'.
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';

@Component({
  selector: 'app-all-superheroes',
  templateUrl: './all-superheroes.component.html',
  styleUrls: ['./all-superheroes.component.css'],
})
export class AllSuperheroesComponent implements OnInit {
  sortingControl = new FormControl('');
  searchControl = new FormControl('');
  allSuperHeroes: SuperHeroes[] = [];

  constructor(
    private superHeroesService: SuperHeroesService,
    public dialog: MatDialog
  ) {}
  ngOnInit(): void {
    this.getApi('', '','');
    this.sortingControl.valueChanges.subscribe((value) => {
      if (value) {
        let sortResult = this.doSorting(value);
        this.getApi(sortResult.sortColumn, sortResult.sortType, '');
      }
    });
  }

  doSorting(value: string) {
    let sortColumn: string = '';
    let sortType: string = '';
    if (value.toLowerCase() === 'id-by-desc') {
      sortColumn = 'id';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'id-by-asc') {
      sortColumn = 'id';
      sortType = 'asc';
    } else if (value.toLowerCase() === 'franchise-by-desc') {
      sortColumn = 'franchise';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'franchise-by-asc') {
      sortColumn = 'franchise';
      sortType = 'asc';
    } else if (value.toLowerCase() === 'gender-by-desc') {
      sortColumn = 'gender';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'gender-by-asc') {
      sortColumn = 'gender';
      sortType = 'asc';
    }
    return {
      sortColumn,
      sortType,
    };
  }

  textSearch() {
    let sortResult = this.doSorting(this.sortingControl.value ?? '');
    this.getApi(
      sortResult.sortColumn,
      sortResult.sortType,
      this.searchControl.value ?? ''
    );
  }

  getApi(sortColumn: string, sortType: string, search: string) {
    this.superHeroesService
      .get(sortColumn, sortType, search)
      .subscribe((response) => {
        this.allSuperHeroes = response;
      });
  }

  deleteItem(id: number) {
    const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
      width: '250px',
      data: { id },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.allSuperHeroes = this.allSuperHeroes.filter((_) => _.id !== id);
      }
    });
  }
}
  • (Line: 15) Declared variable like 'searchControl' of type 'FormControl'.
  • (Line: 60-67) Added a method like 'textSearch()' where we invoke GET API call with the search keyword.
Let's add the HTML in 'all-superheroes.component.html'.
src/app/super-heroes/all-superheroes/all-superheroes.component.html:
<mat-form-field class="example-form-field" style="margin: 0px 6px;">
<mat-label>Search...</mat-label>
<input matInput type="text"  [formControl]="searchControl">
<button  matSuffix mat-icon-button aria-label="Clear" (click)="textSearch()">
  <mat-icon>search</mat-icon>
</button>
</mat-form-field>
Let's add the 'MatIconModule' in the 'AppModule'.
src/app/app.module.ts
import {MatIconModule} from '@angular/material/icon';
// code hidden for display purpose
@NgModule({
  imports: [
    MatIconModule
  ],
})
export class AppModule {}

Implementing Pagination:

Let's change our HTTP GET API call to support the pagination.
src/app/super-heroes/super-heroes.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { SuperHeroes } from './super-heroes';
// existing code hidden for display purpose
@Injectable({
  providedIn: 'root',
})
export class SuperHeroesService {
  constructor(private http: HttpClient) {}

  get(
    sortColumn: string,
    sortType: string,
    searchKey: string,
    currentPage: number,
    pageSize: number
  ): Observable<HttpResponse<any>> {
    let url = `http://localhost:3000/superHeroes?_page=${currentPage}&_limit=${pageSize}`;
    if (sortColumn && sortType) {
      url = `${url}&_sort=${sortColumn}&_order=${sortType}`;
    }

    if (searchKey) {
      url = `${url}&q=${searchKey}`;
    }
    return this.http.get<HttpResponse<any>>(url, { observe: 'response' });
  }
}
  • (Line:19) Here added our pagination query parameters like '_pages' & '_limit'.
Let's update the logic in 'all-superheroes.component.ts'.
src/app/super-heroes/all-superheroes/all-superheroes.component.ts:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
import { SuperHeroes } from '../super-heroes';
import { SuperHeroesService } from '../super-heroes.service';
import { PageEvent } from '@angular/material/paginator';

@Component({
  selector: 'app-all-superheroes',
  templateUrl: './all-superheroes.component.html',
  styleUrls: ['./all-superheroes.component.css'],
})
export class AllSuperheroesComponent implements OnInit {
  sortingControl = new FormControl('');
  searchControl = new FormControl('');
  allSuperHeroes: SuperHeroes[] = [];
  totalRecords: number = 0;
  pageIndex = 0;
  pageSize = 5;

  constructor(
    private superHeroesService: SuperHeroesService,
    public dialog: MatDialog
  ) {}
  ngOnInit(): void {
    this.getApi('', '', '');
    this.sortingControl.valueChanges.subscribe((value) => {
      if (value) {
        let sortResult = this.doSorting(value);
        this.pageIndex = 0;
        this.pageSize = 5;
        this.getApi(sortResult.sortColumn, sortResult.sortType, '');
      }
    });
  }

  doSorting(value: string) {
    let sortColumn: string = '';
    let sortType: string = '';
    if (value.toLowerCase() === 'id-by-desc') {
      sortColumn = 'id';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'id-by-asc') {
      sortColumn = 'id';
      sortType = 'asc';
    } else if (value.toLowerCase() === 'franchise-by-desc') {
      sortColumn = 'franchise';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'franchise-by-asc') {
      sortColumn = 'franchise';
      sortType = 'asc';
    } else if (value.toLowerCase() === 'gender-by-desc') {
      sortColumn = 'gender';
      sortType = 'desc';
    } else if (value.toLowerCase() === 'gender-by-asc') {
      sortColumn = 'gender';
      sortType = 'asc';
    }
    return {
      sortColumn,
      sortType,
    };
  }

  textSearch() {
    let sortResult = this.doSorting(this.sortingControl.value ?? '');
    this.pageIndex = 0;
    this.pageSize = 5;
    this.getApi(
      sortResult.sortColumn,
      sortResult.sortType,
      this.searchControl.value ?? ''
    );
  }

  getApi(sortColumn: string, sortType: string, search: string) {
    this.superHeroesService
      .get(sortColumn, sortType, search, this.pageIndex + 1, this.pageSize)
      .subscribe((response) => {
        this.allSuperHeroes = response.body as SuperHeroes[];
        this.totalRecords = response.headers.get('X-Total-Count')
          ? Number(response.headers.get('X-Total-Count'))
          : 0;
      });
  }

  deleteItem(id: number) {
    const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
      width: '250px',
      data: { id },
    });

    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.allSuperHeroes = this.allSuperHeroes.filter((_) => _.id !== id);
      }
    });
  }

  handlePageEvent(e: PageEvent) {
    
    this.pageIndex = e.pageIndex ;
    this.pageSize = e.pageSize;
    let sortResult = this.doSorting(this.sortingControl.value ?? '');
    this.getApi(
      sortResult.sortColumn,
      sortResult.sortType,
      this.searchControl.value ?? ''
    );
  }
}
  • (Line: 18) To do pagination we are required to know the total number of records on the server. 
  • So we declared a variable like 'totalRecords' to store the total count of items.
  • (Line: 19) Defined the variable like 'pageIndex' to maintain the value of the current page number of the pagination.
  • (Line: 101-112) Here defined the method like 'handlePageEvent' which gets executed for the pagination change.
Let's add the pagination component HTML in 'all-superheroes.component.html'.
src/app/super-heroes/all-superheroes/all-superheroes.component.html:
<div style="margin: 0px 6px">
    <mat-paginator
      [length]="totalRecords"
      [pageSize]="pageSize"
      [pageSizeOptions]="[5, 10, 25, 100]"
      [pageIndex]="pageIndex"
      (page)="handlePageEvent($event)"
      aria-label="Select page"
    >
    </mat-paginator>
</div>
Add the pagination module in 'app.module.ts'
src/app/app.module.ts:
import {MatPaginatorModule} from '@angular/material/paginator';

@NgModule({
  imports: [
    MatPaginatorModule
  ]
})
export class AppModule {}

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on Angular 16 CRUD using the Angular Material UI library. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

Comments

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually