CRUD basically means Create Read Update Delete data from server or database.
In this tutorial, we will learn how to create a project in AngularJS for a student administration portal that will allow the user to create, read (view), edit (update), and delete data using AngularJS.
There are so many editors in the market that can be used for angular development like Webstorm, Aptana, Sublime Text, Eclipse IDE, etc. You can use any of them.
Steps to perform Crud operations
- Step 1 – Create RESTful API with Node js + Express + MySQL
- Step 2 – Create New Angular App
- Step 3 – Create Components in Angular
- Step 4 – Import Modules in app.module.ts
- Step 5 – Create CRUD Routes
- Step 6 – Create Angular Service for REST API Consumption
- Step 7 – Add code In app.component.html
- Step 8 – Create Operation
Create RESTful API with Node js + Express + MySQL
Execute the following command on terminal create node js express, MySQL rest API app:
mkdir node-rest-crud-api
cd node-rest-crud-api
Execute the following command on terminal to install express js framework and MySQL driver with NPM. go to terminal and use the below commands :
npm install express --save
npm install mysql --save
npm install body-parser --save
Create database and table for performing crud operation of node js restful API.
-- Table structure for users CREATE TABLE IF NOT EXISTS users ( id int(11) NOT NULL, name varchar(200) NOT NULL, email varchar(200) NOT NULL, created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE users ADD PRIMARY KEY (id); ALTER TABLE users MODIFY id int(11) NOT NULL AUTO_INCREMENT;
Insert data into the database :
INSERT INTO users (id, name, email, created_at) VALUES (1, 'Test', 'test@g.co', '2019-02-28 13:20:20'), (2, 'john', 'john@g.co', '2019-02-28 13:20:20'), (3, 'tus', 'tuts@g.co', '2019-02-28 13:20:20'), (4, 'tut', 'tut@g.co', '2019-02-28 13:20:20'), (5, 'mhd', 'mhd@g.co', '2019-02-28 13:20:20');
Create a server.js file inside of the node-rest-crud-api folder and put the connection. server.js is the entry point:
Create Components in Angular
Execute the following commands on the terminal to generate components in our angular application. So, open y cour terminal and execute the following command:
ng g c components/add-user
ng g c components/detail-detail
ng g c components/users-list
Import Modules in app.module.ts
Then import modules; so visit src/app directory and open app.module.ts file. Then add the following code into it:
... ... import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [], imports: [ FormsModule, HttpClientModule, ReactiveFormsModule ], providers: [], bootstrap: [] }) export class AppModule { }
Create CRUD Routes
Create routes; with the help of Angular 12 routes. So, you will make the consensus with components to enable the navigation in the CRUD application so add the below code in the app-routing.module.ts file:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UsersListComponent } from './components/users-list/users-list.component'; import { AddUserComponent } from './components/add-user/add-user.component'; import { UserDetailComponent } from './components/user-detail/user-detail.component'; const routes: Routes = [ { path: '', pathMatch: 'full', redirectTo: 'add-user' }, { path: 'users-list', component: UsersListComponent }, { path: 'add-user', component: AddUserComponent }, { path: 'edit-user/:id', component: UserDetailComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Create Angular Service for REST API Consumption
Create services in Angular, so go to the app/service directory in your Angular project and create a User.ts class in it.
Then add the code below to the app/service/User.ts file:
export class User { _id!: String; name!: String; email!: String; }
Then, execute the command to create the crud service file:
ng g s service/crud
Then, add the below code in app/service/crud.service.ts file:
import { Injectable } from '@angular/core'; import { User } from './User'; import { catchError, map } from 'rxjs/operators'; import { Observable, throwError } from 'rxjs'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class CrudService { // Node/Express API REST_API: string = 'http://localhost:3000/'; // Http Header httpHeaders = new HttpHeaders().set('Content-Type', 'application/json'); constructor(private httpClient: HttpClient) { } // Add AddUser(data: User): Observable<any> { let API_URL = `${this.REST_API}/add-user`; return this.httpClient.post(API_URL, data) .pipe( catchError(this.handleError) ) } // Get all objects GetUsers() { return this.httpClient.get(`${this.REST_API}/users`); } // Get single object GetUser(id:any): Observable<any> { let API_URL = `${this.REST_API}/read-user/${id}`; return this.httpClient.get(API_URL, { headers: this.httpHeaders }) .pipe(map((res: any) => { return res || {} }), catchError(this.handleError) ) } // Update updateUser(id:any, data:any): Observable<any> { let API_URL = `${this.REST_API}/update-user/${id}`; return this.httpClient.put(API_URL, data, { headers: this.httpHeaders }) .pipe( catchError(this.handleError) ) } // Delete deleteUser(id:any): Observable<any> { let API_URL = `${this.REST_API}/delete-user/${id}`; return this.httpClient.delete(API_URL, { headers: this.httpHeaders}).pipe( catchError(this.handleError) ) } // Error handleError(error: HttpErrorResponse) { let errorMessage = ''; if (error.error instanceof ErrorEvent) { // Handle client error errorMessage = error.error.message; } else { // Handle server error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } console.log(errorMessage); return throwError(errorMessage); } }
Add code In app.component.html
Create HTML and for crud app in angular. So, visit src/app/app.component.html and update the following code into it:
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand">Angular 12 CRUD Operations with node js express + mysql Demo</a> <div id="navbarNav" class="collapse navbar-collapse"> <ul class="navbar-nav ml-auto "> <li class="nav-item"> <a class="nav-link" routerLinkActive="active" routerLink="/users-list">Show Users</a> </li> <li class="nav-item"> <a class="nav-link" routerLinkActive="active" routerLink="/add-user">Add User</a> </li> </ul> </div> </nav> <router-outlet></router-outlet>
Create Operation
After that, Add the code in add-user.component.ts file:
import { Component, OnInit, NgZone } from '@angular/core'; import { Router } from '@angular/router'; import { CrudService } from './../../service/crud.service'; import { FormGroup, FormBuilder } from "@angular/forms"; @Component({ selector: 'app-add-user', templateUrl: './add-user.component.html', styleUrls: ['./add-user.component.scss'] }) export class AddUserComponent implements OnInit { userForm: FormGroup; constructor( public formBuilder: FormBuilder, private router: Router, private ngZone: NgZone, private crudService: CrudService ) { this.userForm = this.formBuilder.group({ name: [''], email: [''], }) } ngOnInit() { } onSubmit(): any { this.crudService.AddUser(this.userForm.value) .subscribe(() => { console.log('User added successfully!') this.ngZone.run(() => this.router.navigateByUrl('/users-list')) }, (err) => { console.log(err); }); } }
Then, Add the code in add-user.component.html file:
<div class="row justify-content-center mt-5"> <div class="col-md-4"> <form [formGroup]="userForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label>Name</label> <input class="form-control" type="text" formControlName="name" required> </div> <div class="form-group"> <label>Email</label> <input class="form-control" type="email" formControlName="email" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block" type="submit">Add User</button> </div> </form> </div> </div>
Add the code in users-list.component.ts file:
import { Component, OnInit } from '@angular/core'; import { CrudService } from './../../service/crud.service'; @Component({ selector: 'app-users-list', templateUrl: './users-list.component.html', styleUrls: ['./users-list.component.scss'] }) export class UsersListComponent implements OnInit { Users:any = []; constructor(private crudService: CrudService) { } ngOnInit(): void { this.crudService.GetUsers().subscribe(res => { console.log(res) this.Users =res; }); } delete(id:any, i:any) { console.log(id); if(window.confirm('Do you want to go ahead?')) { this.crudService.deleteUser(id).subscribe((res) => { this.Users.splice(i, 1); }) } } }
Add the code in users-list.component.html file:
<div class="container"> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom"> <h2 class="h2">Users List</h2> </div> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Email</th> <th class="text-center" scope="col">Action</th> </tr> </thead> <tbody> <tr *ngFor="let user of Users; let i = index"> <th scope="row">{{user._id}}</th> <td>{{user.name}}</td> <td>{{user.email}}</td> <td class="text-center"> <button class="btn btn-sm btn-primary" routerLink="/edit-user/{{user._id}}">Edit</button> <button class="btn btn-sm btn-danger" (click)="delete(user._id, i)">Delete</button> </tr> </tbody> </table> </div> </div>
Add the code in user-detail.component.ts file
import { Component, OnInit, NgZone } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { CrudService } from './../../service/crud.service'; import { FormGroup, FormBuilder } from "@angular/forms"; @Component({ selector: 'app-user-detail', templateUrl: './user-detail.component.html', styleUrls: ['./user-detail.component.scss'] }) export class UserDetailComponent implements OnInit { getId: any; updateForm: FormGroup; constructor( public formBuilder: FormBuilder, private router: Router, private ngZone: NgZone, private activatedRoute: ActivatedRoute, private crudService: CrudService ) { this.getId = this.activatedRoute.snapshot.paramMap.get('id'); this.crudService.GetUser(this.getId).subscribe(res => { this.updateForm.setValue({ name: res['name'], email: res['email'], }); }); this.updateForm = this.formBuilder.group({ name: [''], email: [''], }) } ngOnInit() { } onUpdate(): any { this.crudService.updateUser(this.getId, this.updateForm.value) .subscribe(() => { console.log('User updated successfully!') this.ngZone.run(() => this.router.navigateByUrl('/users-list')) }, (err) => { console.log(err); }); } }
Add the code in user-detail.component.html file:
<div class="row justify-content-center mt-5"> <div class="col-md-4"> <form [formGroup]="updateForm" (ngSubmit)="onUpdate()"> <div class="form-group"> <label>Name</label> <input class="form-control" type="text" formControlName="name" required> </div> <div class="form-group"> <label>Email</label> <input class="form-control" type="email" formControlName="email" required> </div> <div class="form-group"> <button class="btn btn-primary btn-block" type="submit">Update</button> </div> </form> </div> </div>
Output of all the above coding
Conclusion
In this tutorial, we have learned how to perform CRUD operations using Angular, Node, and MYSQL.