In this article, we will implement CRUD operation in the Angular 14 application.
Now to invoke the above-added command, run the below command in the angular application root folder.
Add route for 'Edit' component into 'FruitModule'.
(Step 2)
(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 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
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
ng new name_of_your_app
Note: While creating the app, you will see a notification to enable routing like '(y/n)' please enter 'y'(yes) For our demo we use routing as well.
Let's explore a 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 configurations of angular.
- src/index.html - Only HTML file of the angular application. It contains the root angular component element like <app-root></app-root>, area for our components to rendered.
- src/main.ts - entry file of our angular application to execute.
- src/app/app.modulet.ts - Entry module.
- src/app/app-routing.module.ts - Entry route module
- app(folder or root component folder) - contains root component like 'AppComponent' consist of files like 'app.component.ts', 'app.component.html', 'app.component.css'.
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 global onto your 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-added 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 access API endpoint like 'http://localhost:3000/fruits'.Install And Configure Bootstrap:
Let's install the bootstrap package into our angular application
npm install bootstrap
Add the bootstrap 'JS' & 'CSS' file path in 'angular.json'.
Add the bootstrap menu to the 'app.component.html' file
src/app/app.component.html:
<nav class="navbar navbar-expand-lg navbar-dark bg-warning"> <div class="container-fluid"> <a class="navbar-brand" href="#">Fruit Bowl</a> </div> </nav> <router-outlet></router-outlet>
- (Line: 1-5) Render the bootstrap menu
- (Line: 6) The 'router-outlet' is the default angular component. The content of every route is rendered into it.
Create A Example Module(Ex: Fruits Module):
Let's create a sample 'Fruits' module along with its route module. Run the below command.
ng generate module fruits --routing
Now add our 'FruitModule' into the imports of the 'AppModule'.
Create A Home Component:
Let's create a child component like 'Home' inside of the 'fruits' module. The 'Home' component will display all the items.
ng generate component fruits/home
Add HomeComponent rout in the 'FruitsRoutingModule'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display purpose import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path: 'fruits/home', component: HomeComponent, }, ];Now make the 'fruits/home' route as the default route by adding a redirection in the 'AppRoutingModule'.
src/app/app-routing.modulet.ts:
// code hidden for display purpose const routes: Routes = [ { path: '', redirectTo: 'fruits/home', pathMatch: 'full', }, ];
Create A Service File:
Create an angular service file where we are going to implement the logic for API calls.
ng generate service fruits/fruits
Now inject the 'HttpClient' instance into the service constructor. The 'HttpClient' provides in-built methods for invoking the API's
src/app/fruits/fruits.service.ts:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root', }) export class FruitsService { constructor(private http: HttpClient) {} }In 'AppModule' add 'HttpClientModule' to the imports array.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http'; // code hidden for display purpose @NgModule({ imports: [ HttpClientModule ], }) export class AppModule { }
Create API Response Model:
Let's create a model for the API response.
ng generate interface fruits/fruits
src/app/fruits/fruits.ts:
export interface Fruits { id: number; name: string; quantity: number; price: number; }
Read Operation:
The Read operation means reading the data from the API.
In 'FruitService' let's implement logic to invoke the API call.
src/app/fruits/fruits.servicet.ts:
get() { return this.http.get<Fruits[]>('http://localhost:3000/fruits'); }
- The 'HttpClient.get<T>()' is to invoke the HTTP Get endpoint.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core'; import { Fruits } from '../fruits'; import { FruitsService } from '../fruits.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) export class HomeComponent implements OnInit { allFruits: Fruits[] = []; constructor(private fruitService: FruitsService) {} ngOnInit(): void { this.get(); } get() { this.fruitService.get().subscribe((data) => { this.allFruits = data; }); } }
- (Line: 5-9) To make 'HomeComponent' as angular component it should be decorated with '@Component' decorator that loads from the '@angular/core'. The 'selector' property for define the component Html element tag. The 'templateUrl' property for to link the component Html file. The 'styleUrls' property for to link the component CSS file.
- (Line: 11) Variable 'allFruits' is of 'Fruits' array type. This variable is to store all API response data into this variable.
- (Line: 19-23) Here defined method like 'get()'. Invoking the get API call in service file. Here 'subscribe()' get executed after completion of the API call. On receiving response assign to the 'allFruits' variable.
- (Line: 15-17) The 'ngOnInit()' is one of the angular component life cycle method. This method executed automatically on invoking our 'HomeComponent'. Inside of this method we invoke our 'get()' method.
src/fruits/home/home.component.html:
<div class="container"> <table class="table"> <thead> <tr> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Quantity</th> <th scope="col">Price</th> </tr> </thead> <tbody> <tr *ngFor="let item of allFruits"> <th scope="row">{{ item.id }}</th> <td>{{ item.name }}</td> <td>{{ item.quantity }}</td> <td>{{ item.price }}</td> </tr> </tbody> </table> </div>
- Angular for databinding bind the we use '{{}}'(string interpolation)
- (Line: 12) The 'allFruits' is array, to loop it over the HTML content we have to use '*ngFor'. In *ngFor we will use array of object like 'allFruits', the 'of' keyword to popsout each item from the array and assign to the variable 'item'
- (Line: 13-16) Rendering the data to the bootstrap table.
Generate A 'Create' Component:
Generate a new child component like 'Create' under the 'fruits' module. This component contains a form for creating the new items.
ng generate component fruits/create
Add route for 'Create' component into 'FruitRouteModule'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display puporse import { CreateComponent } from './create/create.component'; const routes: Routes = [ { path: 'fruits/home', component: HomeComponent, } ];
Create Operation:
Let's implement the logic for invoking the save API call in 'FruitsService'.
src/app/fruits/fruits.service.ts:
create(payload: Fruits) { return this.http.post<Fruits>('http://localhost:3000/fruits', payload); }
- The 'HttpClient.post<T>(payload)' method is invoke the HTTP Post endpoint for saving at the server.
src/app/fruits/create/create.component.ts:
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Fruits } from '../fruits'; import { FruitsService } from '../fruits.service'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'], }) export class CreateComponent implements OnInit { fruitForm: Fruits = { id: 0, name: '', price: 0, quantity: 0, }; constructor(private fruitService:FruitsService, private router:Router) {} ngOnInit(): void {} create(){ this.fruitService.create(this.fruitForm) .subscribe({ next:(data) => { this.router.navigate(["/fruits/home"]) }, error:(err) => { console.log(err); } }) } }
- (Line: 12-17) Declared the 'fruitForm' variable to store the user entered form data.
- (Line: 19-20) Injected the 'FruitsService' and 'Router'.
- (Line: 24-34) Invoking the API call to post the data.
- (Line: 28) On successful saving data to the server, we navigate to the home page.
src/app/fruits/create/create.component.hmtl:
<div class="container"> <legend>Create Item</legend> <form> <div class="mb-3"> <label for="txtName" class="form-label">Name</label> <input type="text" name="name" [(ngModel)] = "fruitForm.name" class="form-control" id="txtName" /> </div> <div class="mb-3"> <label for="txtPrice" class="form-label">Price</label> <input type="number" name="price" [(ngModel)] = "fruitForm.price" class="form-control" id="txtPrice" /> </div> <div class="mb-3"> <label for="txtQuantity" class="form-label">Quantity</label> <input type="number" name="quantity" [(ngModel)] = "fruitForm.quantity" class="form-control" id="txtQuantity" /> </div> <button type="button" (click)="create()" class="btn btn-primary">Create</button> </form> </div>
- Here enable 2-way model binding using '[(ngModel)]'. One more important thing here is that the input element must contain the 'name' attribute for 2-way model binding.
- Click event can be a register like '(name_of_event)' and the event must register with the method so that on raise of event logic inside of the method gets executed.
Add the 'FormModule'(required for ngModel) into the import array of 'FruitsModule'.
src/app/fruits/fruits.module.ts:
// existing code hidden for display purpose import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ FormsModule ] }) export class FruitsModule { }In 'HomeComponent.html' add a button for navigating the 'CreateComponent'.
src/app/fruits/home/home.component.html:
<div class="container"> <div class="row mt-2"> <div class="col col-md-4 offset-md-4"> <a class="btn btn-primary" routerLink="/fruits/create">Create</a> </div> </div> <table class="table"> <!-- code hidden for display purpose --> </table> </div>
- Here 'routerLink' is an angular directive used for anchor tags for navigation.
(Step 2)
(Step 3)
Generate A 'Edit' Component:
Generate new child components like 'Edit' under the 'Fruits' module. This component contains the form for updating the items
ng generate component fruits/edit
Add route for 'Edit' component into 'FruitModule'.
src/app/fruits/fruits-routing.module.ts:
import { EditComponent } from './edit/edit.component'; // existing code hidden for display purpose const routes: Routes = [ { path:'fruits/edit/:id', component: EditComponent } ];
Update Operation:
In our 'FruitService' implement the logic for 2 API calls, one for fetching items by id and another for updating the data.
src/app/fruits/fruits.service.ts:
getById(id: number) { return this.http.get<Fruits>(`http://localhost:3000/fruits/${id}`); } update(payload:Fruits){ return this.http.put(`http://localhost:3000/fruits/${payload.id}`,payload); }
- (Line: 1-3) Invokes the HTTP Get endpoint by 'id' value as a filtering parameter.
- (Line: 5-7) Invokes the HTTP Put endpoint for updating the item. Here 'id' value needs to be passed in the URL and edited data as a payload.
src/app/fruits/edit/edit.component.ts:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Fruits } from '../fruits'; import { FruitsService } from '../fruits.service'; @Component({ selector: 'app-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'], }) export class EditComponent implements OnInit { fruitForm: Fruits = { id: 0, name: '', price: 0, quantity: 0, }; constructor( private route: ActivatedRoute, private router:Router, private fruitService: FruitsService ) {} ngOnInit(): void { this.route.paramMap.subscribe((param) => { var id = Number(param.get('id')); this.getById(id); }); } getById(id: number) { this.fruitService.getById(id).subscribe((data) => { this.fruitForm = data; }); } update() { this.fruitService.update(this.fruitForm) .subscribe({ next:(data) => { this.router.navigate(["/fruits/home"]); }, error:(err) => { console.log(err); } }) } }
- (Line: 12-17) Declared the 'formFruits' variable to store the user form edited data.
- (Line: 18-22) Injected the 'ActivatedRoute', 'Router', 'FruitService'.
- (Line: 24-29) Inside of the 'ngOninit' life cycle method, we try to read the 'id' value from the route using the 'ActivatedRoute.paramMap.subscribe()', then we are invoking our get API call.
- (Line: 31-35) Invokes the API call by 'id' value, on successful the response will be assigned to 'formFruit' variable, so that data gets rendered on the form.
- (Line: 37-47) Invokes the update API, on success navigate back to the 'HomeComponent'.
src/app/fruits/edit/edit.component.html:
<div class="container"> <legend>Edit Item</legend> <form> <div class="mb-3"> <label for="txtName" class="form-label">Name</label> <input type="text" name="name" [(ngModel)] = "fruitForm.name" class="form-control" id="txtName" /> </div> <div class="mb-3"> <label for="txtPrice" class="form-label">Price</label> <input type="number" name="price" [(ngModel)] = "fruitForm.price" class="form-control" id="txtPrice" /> </div> <div class="mb-3"> <label for="txtQuantity" class="form-label">Quantity</label> <input type="number" name="quantity" [(ngModel)] = "fruitForm.quantity" class="form-control" id="txtQuantity" /> </div> <button type="button" (click)="update()" class="btn btn-primary">Update</button> </form> </div>Add the edit button in 'home.component.html' file
src/app/fruits/home/home.component.html:
<!-- existing code hidden for display --> <tr *ngFor="let item of allFruits"> <td> <a class="btn btn-primary" [routerLink]="['/fruits/edit', item.id]">Edit</a> </td> </tr>
- Here we use 'routerLink' inside of '[]' if the URL has a dynamic parameter. On render URL generated as eg:- 'fruits/edits/1'
Delete Operation:
Let's implement delete API logic in 'FruitService'.
src/app/fruits/fruits.service.ts:
delete(id:number){ return this.http.delete<Fruits>(`http://localhost:3000/fruits/${id}`); }
- The 'HttpClient.delete()' invokes the Http Delete request.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core'; import { Fruits } from '../fruits'; import { FruitsService } from '../fruits.service'; declare var window: any; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], }) export class HomeComponent implements OnInit { allFruits: Fruits[] = []; deleteModal: any; idTodelete: number = 0; constructor(private fruitService: FruitsService) {} ngOnInit(): void { this.deleteModal = new window.bootstrap.Modal( document.getElementById('deleteModal') ); this.get(); } get() { this.fruitService.get().subscribe((data) => { this.allFruits = data; }); } openDeleteModal(id: number) { this.idTodelete = id; this.deleteModal.show(); } delete() { this.fruitService.delete(this.idTodelete).subscribe({ next: (data) => { this.allFruits = this.allFruits.filter(_ => _.id != this.idTodelete) this.deleteModal.hide(); }, }); } }
- (Line: 5) Declare window variable type.
- (Line: 14) The variable 'deleteModal' to store the instance of the botstrap modal.
- (Line: 15) The variable 'idToDelete' to store the 'id' value of the item to be deleted.
- (Line: 20-22) Assign the bootstrap modal instance to our 'deleteModal' variable.
- (Line: 33-36) The 'openDeleteModal()' method gets invoked by clicking the delete button. Here we open the delete confirmation modal.
- (Line: 38-45) The 'delete()' method invokes the delete API call on the success we will hide our bootstrap modal and also exclude the item from the 'allFruits' variable.
src/app/fruits/home/home.component.html:
<!-- existing code hidden for display purpose --> <div class="container"> <table class="table"> </thead> <tbody> <tr *ngFor="let item of allFruits"> <td> <a class="btn btn-primary" [routerLink]="['/fruits/edit', item.id]">Edit</a> | <button type="button" (click)="openDeleteModal(item.id)" class="btn btn-danger">Delete</button> </td> </tr> </tbody> </table> </div> <!-- Modal --> <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Warning!</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> Are you sure to delete the item? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-danger" (click)="delete()">Confirm Delete</button> </div> </div> </div> </div>
- (Line: 11) Edit button registered with 'openDeleteModal()' for click event.
- (Line: 20-36) Delete confirmation bootstrap modal, here we have to give 'id' attribute, based on that 'id' attribute we create the bootstrap instance in 'home.component.ts' file.
- (Line: 32) Here 'Confirm Delete' button registered with 'delete()' method for click event.
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 I love to have your feedback, suggestions, and better techniques in the comment section below.
Great tutorial. There are some minor edits needed in the code, but everything works and I learned a lot. Thank you.
ReplyDeleteGracias!! gran tutorial, si bien falto un poco aclarar que el Home se le integra codigo, todo quedo clarisimo!!
ReplyDeleteGreat Job!!
very nice.!!
ReplyDeleteThank for the tutorial, great job!
ReplyDelete