7

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

 1 year ago
source link: https://www.learmoreseekmore.com/2023/05/angular16-crud-example-search-sorting-pagination.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
NET%207%20Web%20API%20CRUD%20Using%20Entity%20Framework%20Core.png

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.
2.jpg
  • 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:


  1. <mat-toolbar color="primary">
  2. <span>Super Heroes</span>
  3. </mat-toolbar>
  4. <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:


  1. import {MatToolbarModule} from '@angular/material/toolbar';
  2. // code hidden for display purpose
  3. @NgModule({
  4. imports: [
  5. MatToolbarModule
  6. export class AppModule { }
1.PNG

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"
2.PNG

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.

3.PNG
Now let's access the endpoint as 'http://localhost:3000/superHeroes'
4.PNG

Create Angular Component 'AllSuperHeroesComponent':

Let's create a new angular component like 'AllSuperHeroesComponent'.
ng generate component super-heroes/all-superheroes --skip-tests
5.PNG
Configure the 'AllSuperHeroesComponent' route in 'AppRoutingModule'
src/app/app-routing.module.ts:


  1. import { AllSuperheroesComponent } from './super-heroes/all-superheroes/all-superheroes.component';
  2. // existing code hidden for display purpose
  3. const routes: Routes = [{
  4. path:'',
  5. 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
6.PNG

src/app/super-heroes/super-heroes.ts:



  1. export interface SuperHeroes {
  2. id: number;
  3. name: string;
  4. imageUrl: string;
  5. franchise: string;
  6. 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
7.PNG
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:


  1. import { Injectable } from '@angular/core';
  2. import {HttpClient} from '@angular/common/http'
  3. @Injectable({
  4. providedIn: 'root'
  5. export class SuperHeroesService {
  6. constructor(private http:HttpClient) { }

Now import 'HttpClientModule' in 'AppModule'.

src/app/app.module.ts:


  1. import { HttpClientModule } from '@angular/common/http';
  2. // existing code hidden for display purpose
  3. @NgModule({
  4. imports: [
  5. HttpClientModule
  6. 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:


  1. get(): Observable<SuperHeroes[]> {
  2. 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:


  1. .example-card {
  2. max-width: 250px;
  3. margin: 10px;
  4. background-color: white;
  5. .app-container {
  6. justify-content: center;
  7. display: flex;
  8. flex-direction: row;
  9. 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:


  1. import { Component, OnInit } from '@angular/core';
  2. import { SuperHeroes } from '../super-heroes';
  3. import { SuperHeroesService } from '../super-heroes.service';
  4. @Component({
  5. selector: 'app-all-superheroes',
  6. templateUrl: './all-superheroes.component.html',
  7. styleUrls: ['./all-superheroes.component.css'],
  8. export class AllSuperheroesComponent implements OnInit {
  9. allSuperHeroes: SuperHeroes[] = [];
  10. constructor(private superHeroesService: SuperHeroesService) {}
  11. ngOnInit(): void {
  12. this.getApi();
  13. getApi() {
  14. this.superHeroesService.get().subscribe((response) => {
  15. 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:


  1. <div class="app-container">
  2. <mat-card class="example-card" *ngFor="let item of allSuperHeroes">
  3. <mat-card-header>
  4. <div mat-card-avatar class="example-header-image"></div>
  5. <mat-card-title >{{ item.name }}</mat-card-title>
  6. <button
  7. mat-mini-fab
  8. matTooltip="Primary"
  9. color="primary"
  10. aria-label="Example mini fab with a heart icon"
  11. {{ item.id }}
  12. </button>
  13. </mat-card-header>
  14. <img mat-card-image src="{{ item.imageUrl }}" alt="" />
  15. <mat-card-content>
  16. <p>Franchise - {{ item.franchise }}</p>
  17. <p>Gender - {{ item.gender }}</p>
  18. </mat-card-content>
  19. </mat-card>
  20. </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 {}
8.PNG

Create Angular Component 'AddSuperHeroesComponent':

Let's create a new angular component like 'AddSuperHeroesComponent'
ng generate component super-heroes/add-superheroes --skip-tests
9.PNG
Let's configure 'AddSuperHeroesComponent' route in 'AppRouteMoudle'.
src/app/app-routing.module.ts:


  1. import { AddSuperheroesComponent } from './super-heroes/add-superheroes/add-superheroes.component';
  2. // existing code hidden for display purpose
  3. const routes: Routes = [{
  4. path:'add',
  5. 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:


  1. add(payload:SuperHeroes){
  2. 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:


  1. import { Component } from '@angular/core';
  2. import { FormBuilder } from '@angular/forms';
  3. import { Router } from '@angular/router';
  4. import { SuperHeroes } from '../super-heroes';
  5. import { SuperHeroesService } from '../super-heroes.service';
  6. @Component({
  7. selector: 'app-add-superheroes',
  8. templateUrl: './add-superheroes.component.html',
  9. styleUrls: ['./add-superheroes.component.css'],
  10. export class AddSuperheroesComponent {
  11. constructor(
  12. private fb: FormBuilder,
  13. private superHeroService: SuperHeroesService,
  14. private router: Router
  15. addSuperHeroForm = this.fb.group({
  16. name: [''],
  17. imageUrl: [''],
  18. franchise: [''],
  19. gender: [''],
  20. noImage =
  21. 'add-preview-image.png';
  22. create() {
  23. this.superHeroService
  24. .add(this.addSuperHeroForm.value as SuperHeroes)
  25. .subscribe(() => {
  26. 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:


  1. .card {
  2. width: 800px;
  3. .card-container {
  4. display: flex;
  5. justify-content: center;
  6. margin-top: 14px;
  7. column-gap: 2em;
  8. .form-container {
  9. display: flex;
  10. flex-direction: column;
  11. .heading{
  12. display: flex;
  13. justify-content: center;
  14. align-items: center;
  15. margin-top: 14px;

Let's add the following HTML 'add-superheroes.component.html'.

src/app/super-heroes/add-superheroes/add-superheroes.component.html:


  1. <div class="heading">
  2. <mat-chip color="primary"> Create A New Super Hereo </mat-chip>
  3. </div>
  4. <div class="card-container">
  5. <mat-card class="card">
  6. <div class="card-container">
  7. <form
  8. class="form-container"
  9. [formGroup]="addSuperHeroForm"
  10. (ngSubmit)="create()"
  11. <mat-form-field appearance="outline" style="width: 400px">
  12. <mat-label>Name</mat-label>
  13. <input matInput formControlName="name" />
  14. </mat-form-field>
  15. <mat-form-field appearance="outline" style="width: 400px">
  16. <mat-label>Image URL</mat-label>
  17. <input matInput formControlName="imageUrl" />
  18. </mat-form-field>
  19. <mat-form-field appearance="outline" style="width: 400px">
  20. <mat-label>Franchise</mat-label>
  21. <mat-select formControlName="franchise">
  22. <mat-option value="marvel">Marvel</mat-option>
  23. <mat-option value="dc">DC</mat-option>
  24. </mat-select>
  25. </mat-form-field>
  26. <mat-radio-group aria-label="Select an option" formControlName="gender">
  27. <mat-radio-button value="male">Male</mat-radio-button>
  28. <mat-radio-button value="female">Female</mat-radio-button>
  29. </mat-radio-group>
  30. <button mat-raised-button color="primary" style="margin: 10px 0px">
  31. </button>
  32. </form>
  33. <div>
  34. <div>
  35. <img
  36. mat-card-lg-image
  37. src="{{
  38. this.addSuperHeroForm.get('imageUrl')?.value
  39. ? this.addSuperHeroForm.get('imageUrl')?.value
  40. : noImage
  41. />
  42. </div>
  43. </div>
  44. </div>
  45. </mat-card>
  46. </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:


  1. import { NgModule } from '@angular/core';
  2. import { BrowserModule } from '@angular/platform-browser';
  3. import { AppRoutingModule } from './app-routing.module';
  4. import { AppComponent } from './app.component';
  5. import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
  6. import {MatFormFieldModule} from '@angular/material/form-field';
  7. import {MatChipsModule} from '@angular/material/chips';
  8. import {MatInputModule} from '@angular/material/input';
  9. import {MatSelectModule} from '@angular/material/select';
  10. import {MatRadioModule} from '@angular/material/radio';
  11. import { MatToolbarModule } from '@angular/material/toolbar';
  12. import { MatButtonModule } from '@angular/material/button';
  13. import { MatCardModule } from '@angular/material/card';
  14. import { AllSuperheroesComponent } from './super-heroes/all-superheroes/all-superheroes.component';
  15. import { HttpClientModule } from '@angular/common/http';
  16. import { AddSuperheroesComponent } from './super-heroes/add-superheroes/add-superheroes.component';
  17. import { ReactiveFormsModule } from '@angular/forms';
  18. @NgModule({
  19. declarations: [AppComponent, AllSuperheroesComponent, AddSuperheroesComponent],
  20. imports: [
  21. BrowserModule,
  22. AppRoutingModule,
  23. BrowserAnimationsModule,
  24. MatToolbarModule,
  25. HttpClientModule,
  26. MatButtonModule,
  27. MatCardModule,
  28. MatFormFieldModule,
  29. MatInputModule,
  30. MatChipsModule,
  31. MatSelectModule,
  32. MatRadioModule,
  33. ReactiveFormsModule
  34. providers: [],
  35. bootstrap: [AppComponent],
  36. 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:


  1. <div class="app-container" style="margin-top: 5px;">
  2. <a mat-raised-button color="primary" routerLink="/add">Add</a>
  3. </div>

(Step 1)

10.PNG
(Step 2)
11.PNG

Create Angular Component 'EditSuperHeroesComponent':

Let's create a new angular component like 'EditSuperHeroesComponent'.
ng generate component super-heroes/edit-superheroes --skip-tests
12.PNG
Now configure the route for 'EditSuperHeroesComponent' in 'AppRoutingModule'.
src/app/app-routing.module.ts:


  1. import { EditSuperheroesComponent } from './super-heroes/edit-superheroes/edit-superheroes.component';
  2. // existing code hidden for display purpose
  3. const routes: Routes = [
  4. path: 'edit/:id',
  5. 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:


  1. getById(id: number): Observable<SuperHeroes> {
  2. return this.http.get<SuperHeroes>(
  3. `http://localhost:3000/superHeroes/${id}`
  4. update(payload: SuperHeroes): Observable<SuperHeroes> {
  5. return this.http.put<SuperHeroes>(
  6. `http://localhost:3000/superHeroes/${payload.id}`,
  7. 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:


  1. .card {
  2. width: 800px;
  3. .card-container {
  4. display: flex;
  5. justify-content: center;
  6. margin-top: 14px;
  7. column-gap: 2em;
  8. .form-container {
  9. display: flex;
  10. flex-direction: column;
  11. .heading{
  12. display: flex;
  13. justify-content: center;
  14. align-items: center;
  15. margin-top: 14px;

Let's add the following logic in 'edit-superheroes.component.ts'.

src/app/super-heroes/edit-superheroes/edit-superheroes.component.ts:


  1. import { Component, OnInit } from '@angular/core';
  2. import { FormBuilder } from '@angular/forms';
  3. import { ActivatedRoute, Router } from '@angular/router';
  4. import { SuperHeroes } from '../super-heroes';
  5. import { SuperHeroesService } from '../super-heroes.service';
  6. @Component({
  7. selector: 'app-edit-superheroes',
  8. templateUrl: './edit-superheroes.component.html',
  9. styleUrls: ['./edit-superheroes.component.css'],
  10. export class EditSuperheroesComponent implements OnInit {
  11. constructor(
  12. private fb: FormBuilder,
  13. private superHeroeService: SuperHeroesService,
  14. private route: ActivatedRoute,
  15. private router: Router
  16. ngOnInit(): void {
  17. this.route.paramMap.subscribe((param) => {
  18. var id = Number(param.get('id'));
  19. this.getById(id);
  20. noImage =
  21. 'previewImages.png';
  22. updateSuperHeroForm = this.fb.group({
  23. id: [0],
  24. name: [''],
  25. imageUrl: [''],
  26. franchise: [''],
  27. gender: [''],
  28. getById(id: number) {
  29. this.superHeroeService.getById(id).subscribe((data) => {
  30. this.updateSuperHeroForm.setValue(data);
  31. update() {
  32. this.superHeroeService.update((this.updateSuperHeroForm.value as SuperHeroes))
  33. .subscribe(() => {
  34. 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:


  1. <div class="heading">
  2. <mat-chip color="primary"> Update Super Hereo </mat-chip>
  3. </div>
  4. <div class="card-container">
  5. <mat-card class="card">
  6. <div class="card-container">
  7. <form
  8. class="form-container"
  9. [formGroup]="updateSuperHeroForm"
  10. (ngSubmit)="update()"
  11. <mat-form-field appearance="outline" style="width: 400px">
  12. <mat-label>Name</mat-label>
  13. <input matInput formControlName="name" />
  14. </mat-form-field>
  15. <mat-form-field appearance="outline" style="width: 400px">
  16. <mat-label>Image URL</mat-label>
  17. <input matInput formControlName="imageUrl" />
  18. </mat-form-field>
  19. <mat-form-field appearance="outline" style="width: 400px">
  20. <mat-label>Franchise</mat-label>
  21. <mat-select formControlName="franchise">
  22. <mat-option value="marvel">Marvel</mat-option>
  23. <mat-option value="dc">DC</mat-option>
  24. </mat-select>
  25. </mat-form-field>
  26. <mat-radio-group aria-label="Select an option" formControlName="gender">
  27. <mat-radio-button value="male">Male</mat-radio-button>
  28. <mat-radio-button value="female">Female</mat-radio-button>
  29. </mat-radio-group>
  30. <button mat-raised-button color="primary" style="margin: 10px 0px">
  31. Update
  32. </button>
  33. </form>
  34. <div>
  35. <div>
  36. <img
  37. mat-card-lg-image
  38. src="{{
  39. this.updateSuperHeroForm.get('imageUrl')?.value
  40. ? this.updateSuperHeroForm.get('imageUrl')?.value
  41. : noImage
  42. />
  43. </div>
  44. </div>
  45. </div>
  46. </mat-card>
  47. </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:


  1. <mat-card-actions>
  2. <a mat-raised-button color="primary" [routerLink]="['/edit', item.id]">Edit</a>
  3. </mat-card-actions>

(Step 1)

13.PNG

(Step 2)

14.PNG

Create Angular Component 'DeleteDialogSuperHeroComponent':

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

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:


  1. delete(id: number) {
  2. 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:


  1. import { Component, Inject } from '@angular/core';
  2. import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
  3. import { SuperHeroesService } from '../super-heroes.service';
  4. @Component({
  5. selector: 'app-delete-dialog-superheroes',
  6. templateUrl: './delete-dialog-superheroes.component.html',
  7. styleUrls: ['./delete-dialog-superheroes.component.css'],
  8. export class DeleteDialogSuperheroesComponent {
  9. constructor(
  10. public dialogRef: MatDialogRef<DeleteDialogSuperheroesComponent>,
  11. @Inject(MAT_DIALOG_DATA) public data: any,
  12. private superHeroesService: SuperHeroesService
  13. confirmDelete() {
  14. this.superHeroesService.delete(this.data.id).subscribe(() => {
  15. 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:


  1. <h1 mat-dialog-title>Delete file</h1>
  2. <div mat-dialog-content>
  3. Would you like to delete ?
  4. </div>
  5. <div mat-dialog-actions>
  6. <button mat-button mat-dialog-close>No</button>
  7. <button mat-button (click)="confirmDelete()" cdkFocusInitial>Confirm Delete</button>
  8. </div>
  • (Line: 7) Here registered with 'confirmDelete()' method.

Now register the 'MatDialogModule' in the 'AppModule'.

src/app/app.module.ts:


  1. import {MatDialogModule} from '@angular/material/dialog';
  2. // existing code hidden for display purpose
  3. @NgModule({
  4. imports: [
  5. MatDialogModule
  6. 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:


  1. import { Component, OnInit } from '@angular/core';
  2. import { MatDialog } from '@angular/material/dialog';
  3. import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
  4. import { SuperHeroes } from '../super-heroes';
  5. import { SuperHeroesService } from '../super-heroes.service';
  6. @Component({
  7. selector: 'app-all-superheroes',
  8. templateUrl: './all-superheroes.component.html',
  9. styleUrls: ['./all-superheroes.component.css'],
  10. export class AllSuperheroesComponent implements OnInit {
  11. allSuperHeroes: SuperHeroes[] = [];
  12. constructor(
  13. private superHeroesService: SuperHeroesService,
  14. public dialog: MatDialog
  15. ngOnInit(): void {
  16. this.getApi();
  17. getApi() {
  18. this.superHeroesService.get().subscribe((response) => {
  19. this.allSuperHeroes = response;
  20. deleteItem(id: number) {
  21. const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
  22. width: '250px',
  23. data: { id },
  24. dialogRef.afterClosed().subscribe((result) => {
  25. if (result) {
  26. 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:


  1. <button mat-raised-button color="warn" (click)="deleteItem(item.id)">Delete</button>
16.PNG

Implement Sorting:

Let's change the HTTP GET API call in the 'SuperHeroService'.
src/app/super-heroes/super-heroes.service.ts:


  1. get(sortColumn: string, sortType: string): Observable<SuperHeroes[]> {
  2. let url = "http://localhost:3000/superHeroes?"
  3. if(sortColumn && sortType){
  4. url = `${url}_sort=${sortColumn}&_order=${sortType}`
  5. 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:


  1. import { Component, OnInit } from '@angular/core';
  2. import { FormControl } from '@angular/forms';
  3. import { MatDialog } from '@angular/material/dialog';
  4. import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
  5. import { SuperHeroes } from '../super-heroes';
  6. import { SuperHeroesService } from '../super-heroes.service';
  7. @Component({
  8. selector: 'app-all-superheroes',
  9. templateUrl: './all-superheroes.component.html',
  10. styleUrls: ['./all-superheroes.component.css'],
  11. export class AllSuperheroesComponent implements OnInit {
  12. sortingControl = new FormControl('');
  13. allSuperHeroes: SuperHeroes[] = [];
  14. constructor(
  15. private superHeroesService: SuperHeroesService,
  16. public dialog: MatDialog
  17. ngOnInit(): void {
  18. this.getApi('', '');
  19. this.sortingControl.valueChanges.subscribe((value) => {
  20. if (value) {
  21. this.doSorting(value);
  22. doSorting(value: string) {
  23. let sortColumn: string = '';
  24. let sortType: string = '';
  25. if (value.toLowerCase() === 'id-by-desc') {
  26. sortColumn = 'id';
  27. sortType = 'desc';
  28. } else if (value.toLowerCase() === 'id-by-asc') {
  29. sortColumn = 'id';
  30. sortType = 'asc';
  31. } else if (value.toLowerCase() === 'franchise-by-desc') {
  32. sortColumn = 'franchise';
  33. sortType = 'desc';
  34. } else if (value.toLowerCase() === 'franchise-by-asc') {
  35. sortColumn = 'franchise';
  36. sortType = 'asc';
  37. } else if (value.toLowerCase() === 'gender-by-desc') {
  38. sortColumn = 'gender';
  39. sortType = 'desc';
  40. } else if (value.toLowerCase() === 'gender-by-asc') {
  41. sortColumn = 'gender';
  42. sortType = 'asc';
  43. this.getApi(sortColumn, sortType);
  44. getApi(sortColumn: string, sortType: string) {
  45. this.superHeroesService.get(sortColumn, sortType).subscribe((response) => {
  46. this.allSuperHeroes = response;
  47. deleteItem(id: number) {
  48. const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
  49. width: '250px',
  50. data: { id },
  51. dialogRef.afterClosed().subscribe((result) => {
  52. if (result) {
  53. 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:


  1. <div class="filter-container">
  2. <mat-form-field appearance="fill" >
  3. <mat-label> -Sorting- </mat-label>
  4. <mat-select [formControl]="sortingControl">
  5. <mat-option value="">-select-</mat-option>
  6. <mat-option value="id-by-desc">Id By Desc</mat-option>
  7. <mat-option value="id-by-asc">Id By Asc</mat-option>
  8. <mat-option value="franchise-by-desc">Franchise By Desc</mat-option>
  9. <mat-option value="franchise-by-asc">Franchise By Asc</mat-option>
  10. <mat-option value="gender-by-desc">Gender By Desc</mat-option>
  11. <mat-option value="gender-by-asc">Gender By Asc</mat-option>
  12. </mat-select>
  13. </mat-form-field>
  14. </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;
}
17.PNG

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:


  1. sortColumn: string,
  2. sortType: string,
  3. searchKey: string
  4. ): Observable<SuperHeroes[]> {
  5. let url = 'http://localhost:3000/superHeroes?';
  6. if (sortColumn && sortType) {
  7. url = `${url}_sort=${sortColumn}&_order=${sortType}`;
  8. if (searchKey) {
  9. if (url.indexOf('&') > -1) {
  10. url = `${url}&q=${searchKey}`;
  11. } else {
  12. url = `${url}q=${searchKey}`;
  13. 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:


  1. import { Component, OnInit } from '@angular/core';
  2. import { FormControl } from '@angular/forms';
  3. import { MatDialog } from '@angular/material/dialog';
  4. import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
  5. import { SuperHeroes } from '../super-heroes';
  6. import { SuperHeroesService } from '../super-heroes.service';
  7. @Component({
  8. selector: 'app-all-superheroes',
  9. templateUrl: './all-superheroes.component.html',
  10. styleUrls: ['./all-superheroes.component.css'],
  11. export class AllSuperheroesComponent implements OnInit {
  12. sortingControl = new FormControl('');
  13. searchControl = new FormControl('');
  14. allSuperHeroes: SuperHeroes[] = [];
  15. constructor(
  16. private superHeroesService: SuperHeroesService,
  17. public dialog: MatDialog
  18. ngOnInit(): void {
  19. this.getApi('', '','');
  20. this.sortingControl.valueChanges.subscribe((value) => {
  21. if (value) {
  22. let sortResult = this.doSorting(value);
  23. this.getApi(sortResult.sortColumn, sortResult.sortType, '');
  24. doSorting(value: string) {
  25. let sortColumn: string = '';
  26. let sortType: string = '';
  27. if (value.toLowerCase() === 'id-by-desc') {
  28. sortColumn = 'id';
  29. sortType = 'desc';
  30. } else if (value.toLowerCase() === 'id-by-asc') {
  31. sortColumn = 'id';
  32. sortType = 'asc';
  33. } else if (value.toLowerCase() === 'franchise-by-desc') {
  34. sortColumn = 'franchise';
  35. sortType = 'desc';
  36. } else if (value.toLowerCase() === 'franchise-by-asc') {
  37. sortColumn = 'franchise';
  38. sortType = 'asc';
  39. } else if (value.toLowerCase() === 'gender-by-desc') {
  40. sortColumn = 'gender';
  41. sortType = 'desc';
  42. } else if (value.toLowerCase() === 'gender-by-asc') {
  43. sortColumn = 'gender';
  44. sortType = 'asc';
  45. return {
  46. sortColumn,
  47. sortType,
  48. textSearch() {
  49. let sortResult = this.doSorting(this.sortingControl.value ?? '');
  50. this.getApi(
  51. sortResult.sortColumn,
  52. sortResult.sortType,
  53. this.searchControl.value ?? ''
  54. getApi(sortColumn: string, sortType: string, search: string) {
  55. this.superHeroesService
  56. .get(sortColumn, sortType, search)
  57. .subscribe((response) => {
  58. this.allSuperHeroes = response;
  59. deleteItem(id: number) {
  60. const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
  61. width: '250px',
  62. data: { id },
  63. dialogRef.afterClosed().subscribe((result) => {
  64. if (result) {
  65. 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:


  1. <mat-form-field class="example-form-field" style="margin: 0px 6px;">
  2. <mat-label>Search...</mat-label>
  3. <input matInput type="text" [formControl]="searchControl">
  4. <button matSuffix mat-icon-button aria-label="Clear" (click)="textSearch()">
  5. <mat-icon>search</mat-icon>
  6. </button>
  7. </mat-form-field>

Let's add the 'MatIconModule' in the 'AppModule'.

src/app/app.module.ts


  1. import {MatIconModule} from '@angular/material/icon';
  2. // code hidden for display purpose
  3. @NgModule({
  4. imports: [
  5. MatIconModule
  6. export class AppModule {}
18.PNG

Implementing Pagination:

Let's change our HTTP GET API call to support the pagination.
src/app/super-heroes/super-heroes.service.ts:


  1. import { Injectable } from '@angular/core';
  2. import { HttpClient, HttpResponse } from '@angular/common/http';
  3. import { Observable } from 'rxjs';
  4. import { SuperHeroes } from './super-heroes';
  5. // existing code hidden for display purpose
  6. @Injectable({
  7. providedIn: 'root',
  8. export class SuperHeroesService {
  9. constructor(private http: HttpClient) {}
  10. sortColumn: string,
  11. sortType: string,
  12. searchKey: string,
  13. currentPage: number,
  14. pageSize: number
  15. ): Observable<HttpResponse<any>> {
  16. let url = `http://localhost:3000/superHeroes?_page=${currentPage}&_limit=${pageSize}`;
  17. if (sortColumn && sortType) {
  18. url = `${url}&_sort=${sortColumn}&_order=${sortType}`;
  19. if (searchKey) {
  20. url = `${url}&q=${searchKey}`;
  21. 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:


  1. import { Component, OnInit } from '@angular/core';
  2. import { FormControl } from '@angular/forms';
  3. import { MatDialog } from '@angular/material/dialog';
  4. import { DeleteDialogSuperheroesComponent } from '../delete-dialog-superheroes/delete-dialog-superheroes.component';
  5. import { SuperHeroes } from '../super-heroes';
  6. import { SuperHeroesService } from '../super-heroes.service';
  7. import { PageEvent } from '@angular/material/paginator';
  8. @Component({
  9. selector: 'app-all-superheroes',
  10. templateUrl: './all-superheroes.component.html',
  11. styleUrls: ['./all-superheroes.component.css'],
  12. export class AllSuperheroesComponent implements OnInit {
  13. sortingControl = new FormControl('');
  14. searchControl = new FormControl('');
  15. allSuperHeroes: SuperHeroes[] = [];
  16. totalRecords: number = 0;
  17. pageIndex = 0;
  18. pageSize = 5;
  19. constructor(
  20. private superHeroesService: SuperHeroesService,
  21. public dialog: MatDialog
  22. ngOnInit(): void {
  23. this.getApi('', '', '');
  24. this.sortingControl.valueChanges.subscribe((value) => {
  25. if (value) {
  26. let sortResult = this.doSorting(value);
  27. this.pageIndex = 0;
  28. this.pageSize = 5;
  29. this.getApi(sortResult.sortColumn, sortResult.sortType, '');
  30. doSorting(value: string) {
  31. let sortColumn: string = '';
  32. let sortType: string = '';
  33. if (value.toLowerCase() === 'id-by-desc') {
  34. sortColumn = 'id';
  35. sortType = 'desc';
  36. } else if (value.toLowerCase() === 'id-by-asc') {
  37. sortColumn = 'id';
  38. sortType = 'asc';
  39. } else if (value.toLowerCase() === 'franchise-by-desc') {
  40. sortColumn = 'franchise';
  41. sortType = 'desc';
  42. } else if (value.toLowerCase() === 'franchise-by-asc') {
  43. sortColumn = 'franchise';
  44. sortType = 'asc';
  45. } else if (value.toLowerCase() === 'gender-by-desc') {
  46. sortColumn = 'gender';
  47. sortType = 'desc';
  48. } else if (value.toLowerCase() === 'gender-by-asc') {
  49. sortColumn = 'gender';
  50. sortType = 'asc';
  51. return {
  52. sortColumn,
  53. sortType,
  54. textSearch() {
  55. let sortResult = this.doSorting(this.sortingControl.value ?? '');
  56. this.pageIndex = 0;
  57. this.pageSize = 5;
  58. this.getApi(
  59. sortResult.sortColumn,
  60. sortResult.sortType,
  61. this.searchControl.value ?? ''
  62. getApi(sortColumn: string, sortType: string, search: string) {
  63. this.superHeroesService
  64. .get(sortColumn, sortType, search, this.pageIndex + 1, this.pageSize)
  65. .subscribe((response) => {
  66. this.allSuperHeroes = response.body as SuperHeroes[];
  67. this.totalRecords = response.headers.get('X-Total-Count')
  68. ? Number(response.headers.get('X-Total-Count'))
  69. deleteItem(id: number) {
  70. const dialogRef = this.dialog.open(DeleteDialogSuperheroesComponent, {
  71. width: '250px',
  72. data: { id },
  73. dialogRef.afterClosed().subscribe((result) => {
  74. if (result) {
  75. this.allSuperHeroes = this.allSuperHeroes.filter((_) => _.id !== id);
  76. handlePageEvent(e: PageEvent) {
  77. this.pageIndex = e.pageIndex ;
  78. this.pageSize = e.pageSize;
  79. let sortResult = this.doSorting(this.sortingControl.value ?? '');
  80. this.getApi(
  81. sortResult.sortColumn,
  82. sortResult.sortType,
  83. 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:


  1. <div style="margin: 0px 6px">
  2. <mat-paginator
  3. [length]="totalRecords"
  4. [pageSize]="pageSize"
  5. [pageSizeOptions]="[5, 10, 25, 100]"
  6. [pageIndex]="pageIndex"
  7. (page)="handlePageEvent($event)"
  8. aria-label="Select page"
  9. </mat-paginator>
  10. </div>

Add the pagination module in 'app.module.ts'

src/app/app.module.ts:


  1. import {MatPaginatorModule} from '@angular/material/paginator';
  2. @NgModule({
  3. imports: [
  4. MatPaginatorModule
  5. export class AppModule {}
19.PNG

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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK