In this article, we are going to implement a CRUD example sample of Angular(v14) using the Angular Material(v14) UI components.
Let's explore a few default files in the angular project.
Now to invoke the above-added command, run the below command in the angular application root folder.
Let's configure the 'EditStudentComponent' route in the 'AppRoutingModule'.
(Step 3)
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(*.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(14) Application:
Let's create the Angular(14) application to accomplish our demo.
Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application.
npm install -g @angular/cli
Run the below command to create Angular application
ng new name_of_your_project
While creating the app CLI needs a few inputs from us:
- (1) Add the Angular routing
- (2) Angular support styles sheet files like 'CSS', 'SCSS', 'Sass', 'Less'. For this demo, I choose 'CSS' file type.
- 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 configurations 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.module.ts - entry route module.
- app(folder or root component folder) - contains root component like 'AppComponent' that consists of files like 'app.component.ts', 'app.component.html', 'app.component.css'.
Install Angular Material Library:
Let's install the Angular Material library into our application
ng add @angular/material
While installing the library CLI expects a few inputs from us:- (1)It asks us to choose a theme
- (2)Ask us to set up angular typography styles, we can say 'yes' to it.
- (3) It asks us to enable animations or not, we can say 'yes' to it.
Toolbar Angular Material Component To Create Menu:
Let's use the Angular Material Toolbar component for 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>Students</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 components or page-level components get rendered.
src/app/app.module.ts:
import { MatToolbarModule } from '@angular/material/toolbar'; // existing 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"
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 access API endpoint like 'http://localhost:3000/students'.
Create Angular Component 'AllStudents':
Let's create a new angular component like 'AllStudentsComponent'.
ng generate component allStudents --skip-tests
Configure route for 'AllStudentsComponent' component in 'AppRoutingModule'.
src/app/app-routing.module.ts:
import { AllStudentsComponent } from './all-students/all-students.component'; //existing code hidden for display purpose const routes: Routes = [ { path: '', component: AllStudentsComponent, }, ];
- Here empty path represents that is the home URL and is mapped to our 'AllStudentComponent'.
Create Angular Service 'Students':
Let's create an angular service like 'StudentsService', where we are going to write our API calls logic.
ng generate service students --skip-tests
Now inject the 'HttpClient' instance into the service constructor. The 'HttpClient' provides in-built methods for invoking the API calls.
src/app/students.service.ts:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class StudentsService { constructor(private httpClient: HttpClient) {} }Now import 'HttpClientModule' in the 'AppModule'.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http'; // existing code hidden for display purpose @NgModule({ imports: [ HttpClientModule ] }) export class AppModule {}
Create API Response Model 'Student':
Let's create an API response model like 'Student'.
ng generate interface student
src/app/student.ts:
export interface Student { id: number; firstName: string; lastName: string; gender: string; age: number; }
Initial CSS To Sylte.css File:
Let's add a small flex design style in our 'style.css' for to center the content.
src/style.css:
.container { display: flex; align-items: center; justify-content: center; }
Read Operation:
The read operation means fetching the data from the API and then bind to the UI.
In our 'StudentsService' let's implement our logic to invoke the get API call.
src/app/student.service.ts:
get(): Observable<Student[]> { return this.httpClient.get<Student[]>('http://localhost:3000/students'); }Let's add a few CSS styles to 'all-students.component.html' file
src/app/all-students/all-students.component.html:
table { width: 80%; } .allstudents-container { padding: 20px; }Let's add the following logic into the 'app.component.ts'.
src/app/app.component.html:
import { Component, OnInit } from '@angular/core'; import { Student } from '../student'; import { StudentsService } from '../students.service'; @Component({ selector: 'app-all-students', templateUrl: './all-students.component.html', styleUrls: ['./all-students.component.css'], }) export class AllStudentsComponent implements OnInit { allStudentsSource: Student[] = []; displayedColumns: string[] = ['id', 'firstName', 'gender', 'lastName', 'age']; constructor(private studentService: StudentsService) {} ngOnInit(): void { this.get(); } get() { this.studentService.get().subscribe((data) => { this.allStudentsSource = data; }); } }
- (Line: 5-10) To make our 'AllStudentsComponent' 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 'allStudentSource' variable to store the API response data.
- (Line: 12) The 'displayedColumns' variable to register the columns we want to display on the material table. The order of columns of the material table depends on the order in which columns are registered with the 'displayColumns' variable,
- (Line: 14) Injected our 'StudentService'.
- (Line: 20-24) Invoking the GET API call and API response stored to the 'allStudentsSource' variable.
- (Line: 16-18) The 'ngOnInit' is an angular life cycle method that executes on component renders. So in this method, we will invoke our 'get()' method.
src/app/app.component.html:
<div class="container allstudents-container"> <table mat-table [dataSource]="allStudentsSource" class="mat-elevation-z8"> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef>Id</th> <td mat-cell *matCellDef="let element">{{ element.id }}</td> </ng-container> <ng-container matColumnDef="firstName"> <th mat-header-cell *matHeaderCellDef>First Name</th> <td mat-cell *matCellDef="let element">{{ element.firstName }}</td> </ng-container> <ng-container matColumnDef="lastName"> <th mat-header-cell *matHeaderCellDef>Last Name</th> <td mat-cell *matCellDef="let element">{{ element.lastName }}</td> </ng-container> <ng-container matColumnDef="gender"> <th mat-header-cell *matHeaderCellDef>Gender</th> <td mat-cell *matCellDef="let element">{{ element.gender }}</td> </ng-container> <ng-container matColumnDef="age"> <th mat-header-cell *matHeaderCellDef>Age</th> <td mat-cell *matCellDef="let element">{{ element.age }}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> </table> </div>
- (Line: 12) The 'dataSource' is material table property that expects array of data that needs to be rendered on the table.
- The 'matColumnDef' value must be one of the values registered in the 'displayedColumns' variable.
- The 'matCellDef' attributes can read the each individual item from the 'dataSource' variable.
- In angular data binding done with '{{}}' (string interpolation)
src/app/app.module.ts:
import { MatTableModule } from '@angular/material/table'; // existing code hidden for display purpose @NgModule({ imports: [ MatTableModule, ] }) export class AppModule {}
Create Angular Component 'AddStudent':
Let's create a new angular component like 'AddStudent'.
ng generate component add-student --skip-tests
Let's add the route for 'AddStudentComponent' in the 'AppRoutingModule'.
src/app/app-routing.module.ts:
import { AddStudentComponent } from './add-student/add-student.component'; // existing code hidden for display purpose const routes: Routes = [ { path:'add-student', component: AddStudentComponent } ];
Create Operation:
Let's implement the logic to invoke the HTTP POST API call to create an item in the 'StudentsService'.
src/app/students.service.ts:
create(payload:Student){ return this.httpClient.post<Student>('http://localhost:3000/students', payload); }
- The 'HttpClient.post<T>()' method invokes the HTTP Post endpoint to create an item.
src/app/add-student/add-student.component.ts:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Student } from '../student'; import { StudentsService } from '../students.service'; @Component({ selector: 'app-add-student', templateUrl: './add-student.component.html', styleUrls: ['./add-student.component.css'], }) export class AddStudentComponent implements OnInit { studentForm: Student = { id: 0, firstName: '', lastName: '', gender: 'Male', age: 0, }; constructor( private studentService: StudentsService, private router: Router ) {} ngOnInit(): void {} create() { this.studentService.create(this.studentForm).subscribe(() => { this.router.navigate(['/']); }); } }
- (Line: 12-18) The 'studentForm' object will be used for our form model binding.
- (Line: 21-22) The 'StudentService' and 'Router' services are injected into our constructor.
- (Line: 27-31) The 'create()' method will be registered for the form submit button click event. Here we invoke our HTTP Post API call. On API call success navigate the page back to the home page.
Let's add a few CSS in 'add-student.component.css'
src/app/add-student/add-student.component.css:
.form-element{ width: 500px; } .add-student-container{ padding: 20px; }Let's add the following HTML content to the 'add-student.component.html'.
src/app/add-student/add-student.component.html:
<div class="container add-student-container"> <div> <mat-card> <h3 style="text-align: center">Add New Students Data</h3> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>First Name</mat-label> <input matInput [(ngModel)] ="studentForm.firstName" /> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>Last Name</mat-label> <input matInput [(ngModel)] ="studentForm.lastName"/> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>Gender</mat-label> <mat-select [(ngModel)] ="studentForm.gender"> <mat-option value="Male">Male</mat-option> <mat-option value="Female">Female</mat-option> </mat-select> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>Age</mat-label> <input matInput type="number" [(ngModel)] ="studentForm.age"/> </mat-form-field> </div> <div> <button mat-raised-button color="primary" (click)="create()">Create</button> </div> </mat-card> </div> </div>
- (Line: 3) The 'mat-card' used an angular material card component.
- The 'mat-form-field' means angular material form field component. Here we used angular form binding using '[(ngModel)]'.
- (Line: 34) The material button click event registered with the 'create()' method.
src/app/app.module.ts:
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { MatCardModule } from '@angular/material/card'; import { MatSelectModule } from '@angular/material/select'; import {MatButtonModule} from '@angular/material/button'; import { FormsModule } from '@angular/forms'; // existing code hidden for display purpose @NgModule({ imports: [ MatFormFieldModule, MatInputModule, MatCardModule, MatSelectModule, MatButtonModule, FormsModule ] }) export class AppModule {}
- Here we can observe imported all required material modules. The 'ForModule' is an angular module imported because we are using '[(ngModel)]' for form binding.
src/app/all-students.component.ts:
<div class="container allstudents-container"> <a mat-raised-button color="primary" routerLink="/add-student">Add</a> </div>(Step 1)
(Step 2)
(Step 3)
Create Angular Component 'EditStudent':
Let's create a new angular component like 'EditStudent'.
ng generate component edit-student --skip-tests
src/app/app-routing.module.ts:
import { EditStudentComponent } from './edit-student/edit-student.component'; // existing code hidden for display purpose const routes: Routes = [ { path: 'edit-student/:id', component: EditStudentComponent, }, ];
- Here path contains a dynamic placeholder ':id' which can be our item 'id' value in the URL.
Update Operation:
Let's implement the logic to invoke the HTTP PUT API call to update the item in our 'StudentsService'.
src/app/students.service.ts:
getById(id: number): Observable<Student> { return this.httpClient.get<Student>(`http://localhost:3000/students/${id}`); } update(payload: Student): Observable<Student> { return this.httpClient.put<Student>( `http://localhost:3000/students/${payload.id}`, payload ); }
- (Line: 1-3) Here invoking the HTTP GET Endpoint by 'id' value which is the item to be edited.
- (Line: 5-10) The 'HttpClient.put()' method invokes updating the item.
src/app/edit-student/edit-student.component.css:
.form-element { width: 500px; } .add-student-container { padding: 20px; }Let's add the following logic to 'edit-student.component.ts' file
src/app/edit-student/edit-student.component.ts:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Student } from '../student'; import { StudentsService } from '../students.service'; @Component({ selector: 'app-edit-student', templateUrl: './edit-student.component.html', styleUrls: ['./edit-student.component.css'], }) export class EditStudentComponent implements OnInit { studentForm: Student = { id: 0, firstName: '', lastName: '', gender: 'Male', age: 0, }; constructor( private studentService: StudentsService, private router: Router, private route: ActivatedRoute ) {} ngOnInit(): void { this.route.paramMap.subscribe((param) => { var id = Number(param.get('id')); this.getById(id); }); } getById(id: number) { this.studentService.getById(id).subscribe((data) => { this.studentForm = data; }); } update() { this.studentService.update(this.studentForm).subscribe(() => { this.router.navigate(['/']); }); } }
- (Line: 23) Injected the 'ActivatedRoute' that loads from the '@angular/router'
- (Line: 27-30) Reading the 'id' value from the URL.
- (Line: 33) The HTTP GET endpoint by 'id' value for to update the item.
- (Line: 39-43) Invoking the Update API call.
src/app/edit-student/edit-student.component.html:
<div class="container add-student-container"> <div> <mat-card> <h3 style="text-align: center">Update Students Data</h3> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>First Name</mat-label> <input matInput [(ngModel)] ="studentForm.firstName" /> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>Last Name</mat-label> <input matInput [(ngModel)] ="studentForm.lastName"/> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>Gender</mat-label> <mat-select [(ngModel)] ="studentForm.gender"> <mat-option value="Male">Male</mat-option> <mat-option value="Female">Female</mat-option> </mat-select> </mat-form-field> </div> <div> <mat-form-field appearance="outline" class="form-element"> <mat-label>Age</mat-label> <input matInput type="number" [(ngModel)] ="studentForm.age"/> </mat-form-field> </div> <div> <button mat-raised-button color="primary" (click)="update()">Update</button> </div> </mat-card> </div> </div>Let's configure the edit button in 'AllStudentComponent'.
src/app/all-students/all-students.component.ts:
displayedColumns: string[] = ['id', 'firstName', 'gender', 'lastName', 'age','actions'];
- Here 'actions' is the additional column name configured.
<ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef>Actions</th> <td mat-cell *matCellDef="let element"> <a [routerLink]="['/edit-student', element.id]" ><mat-icon aria-hidden="false" aria-label="Example home icon" fontIcon="edit" > </mat-icon ></a> </td> </ng-container>
- Here is our new 'actions' column. Here we can observe an anchor tag with an edit page route and here we use a material edit icon.
src/app.module.ts:
import {MatIconModule} from '@angular/material/icon'; // existing code hidden for display purpose @NgModule({ imports: [ MatIconModule ] }) export class AppModule {}(Step 1)(Step 2)
(Step 3)
Delete Operation:
Let's implement the logic to invoke the HTTP DELETE endpoint for deleting an item in the 'StudentService'.
src/app/students.service.ts:
delete(id: number) { return this.httpClient.delete(`http://localhost:3000/students/${id}`); }
- Here 'HttpClient.delete()' method invokes the HTTP Delete endpoint.
ng generate component delete-dialog-student --skip-tests
Let's add the following logic into the 'delete-dialog-student.component.ts'
src/app/delete-dialog-student/delete-dialog-student.component.ts:
import { Component, Inject, OnInit } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { StudentsService } from '../students.service'; @Component({ selector: 'app-delete-dialog-student', templateUrl: './delete-dialog-student.component.html', styleUrls: ['./delete-dialog-student.component.css'], }) export class DeleteDialogStudentComponent implements OnInit { constructor( public dialogRef: MatDialogRef<DeleteDialogStudentComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private studentService: StudentsService ) {} ngOnInit(): void {} confirmDelete() { this.studentService.delete(this.data.id).subscribe(() => { this.dialogRef.close(this.data.id); }); } }
- (Line: 12) The 'MatDialogRef' loads from the '@angular/material/dialog. The 'MatDialogRef' 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 'StudentService'.
- (Line: 19-23) The 'confirmDelete' method invokes the HTTP Delete API call. After API call completes we will close the dialog by using the 'dialog.close()' method.
src/app/delete-dialog-student/delete-dialog-student.component.html:
<h1 mat-dialog-title>Delete Item</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>Ok</button> </div>
- (Line: 7) Here registered with the 'confirmDelete' method.
src/app-routing.module.ts:
import {MatDialogModule} from '@angular/material/dialog'; @NgModule({ imports: [ MatDialogModule ] }) export class AppModule {}Let's add the following logic into the 'all-students.component.ts' file.
src/app/all-students/all-students.component.ts:
import { Component, OnInit } from '@angular/core'; import { Student } from '../student'; import { StudentsService } from '../students.service'; import { MatDialog } from '@angular/material/dialog'; import { DeleteDialogStudentComponent } from '../delete-dialog-student/delete-dialog-student.component'; @Component({ selector: 'app-all-students', templateUrl: './all-students.component.html', styleUrls: ['./all-students.component.css'], }) export class AllStudentsComponent implements OnInit { allStudentsSource: Student[] = []; displayedColumns: string[] = [ 'id', 'firstName', 'gender', 'lastName', 'age', 'actions', ]; constructor( private studentService: StudentsService, public dialog: MatDialog ) {} ngOnInit(): void { this.get(); } get() { this.studentService.get().subscribe((data) => { this.allStudentsSource = data; }); } openDeleteModal(id: number) { const dialogRef = this.dialog.open(DeleteDialogStudentComponent, { width: '250px', data: { id }, }); dialogRef.afterClosed().subscribe((result) => { if (result) { this.allStudentsSource = this.allStudentsSource.filter( (_) => _.id !== id ); } }); } }
- (Line: 25) Inject the 'MatDailog' that loads from the '@angular/material/dialog.
- (Line: 39-42) Open the material dialog box and also we pass the item 'id' value that needs to be deleted.
- (Line: 44-51) The 'afterClosed()' method executes after closing the material dialog. Here it receives the item 'id' value when we click on the 'Ok' button on the dialog,
<ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef>Actions</th> <td mat-cell *matCellDef="let element"> <a [routerLink]="['/edit-student', element.id]" ><mat-icon aria-hidden="false" aria-label="Example home icon" fontIcon="edit" > </mat-icon ></a> <mat-icon (click)="openDeleteModal(element.id)" aria-hidden="false" aria-label="Example delete icon" fontIcon="delete" > </mat-icon> </td> </ng-container>
- (Line: 12-18) Rendered the material delete icon whose click event registered with 'openDeleteModal()' method.
Support Me!
Buy Me A Coffee
PayPal Me
Video Session:
Wrapping Up:
Hopefully, I think this article delivered some useful information on Angular 14 CRUD using the Angular Material UI library. using I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment