Angular 12 + Node js Express + MySQL CRUD Example

Creating CRUD app with Angular 12 + Node JS Express js + MySQL; In this tutorial,i am going to show you how to create crud app in angular 12 + node js express + MySQL with rest Apis.

Angular 12 crud + nodejs + express+ MySQL example; I will create simple crud app in angular 12 + node js+ express+ MySQL for create, read, update and delete data from MySQL database.

Angular 12 + Node js Express + MySQL CRUD Tutorial with Example

  • 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

Step 1 – 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 initialize node js + express app:

npm init --yes

npm install

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 perform 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 database :

INSERT INTO users (id, name, email, created_at) VALUES
  (1, 'Test', '[email protected]', '2019-02-28 13:20:20'),
  (2, 'john', '[email protected]', '2019-02-28 13:20:20'),
  (3, 'tus', '[email protected]', '2019-02-28 13:20:20'),
  (4, 'tut', '[email protected]', '2019-02-28 13:20:20'),
  (5, 'mhd', '[email protected]', '2019-02-28 13:20:20');

Create server.js file inside of node-rest-crud-api folder and put the connection. server.js is entry point:

var express = require('express');
 var app = express();
 var bodyParser = require('body-parser');
 app.use(bodyParser.json());
 app.use(bodyParser.urlencoded({
     extended: true
 }));
 // default route
 app.get('/', function (req, res) {
     return res.send({ error: true, message: 'hello' })
 });
 // set port
 app.listen(3000, function () {
     console.log('Node app is running on port 3000');
 });
 module.exports = app;

Create database connection for create, read, update and delete data into database :

// connection configurations
 var dbConn = mysql.createConnection({
     host: 'localhost',
     user: 'root',
     password: '',
     database: 'node_js_api'
 });
 // connect to database
 dbConn.connect(); 

Now open again server.js file and add following code into it”

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
 
 
// default route
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});
// connection configurations
var dbConn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'node_js_api'
});
 
// connect to database
dbConn.connect(); 
// Retrieve all users 
app.get('/users', function (req, res) {
    dbConn.query('SELECT * FROM users', function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'users list.' });
    });
});
// Retrieve user with id 
app.get('/read-user/:id', function (req, res) {
 
    let user_id = req.params.id;
 
    if (!user_id) {
        return res.status(400).send({ error: true, message: 'Please provide user_id' });
    }
 
    dbConn.query('SELECT * FROM users where id=?', user_id, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results[0], message: 'users list.' });
    });
 
});
// Add a new user  
app.post('/add-user', function (req, res) {
 
    let user = req.body.user;
 
    if (!user) {
        return res.status(400).send({ error:true, message: 'Please provide user' });
    }
 
    dbConn.query("INSERT INTO users SET ? ", { user: user }, function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
    });
});
//  Update user with id
app.put('/update-user', function (req, res) {
 
    let user_id = req.body.user_id;
    let user = req.body.user;
 
    if (!user_id || !user) {
        return res.status(400).send({ error: user, message: 'Please provide user and user_id' });
    }
 
    dbConn.query("UPDATE users SET user = ? WHERE id = ?", [user, user_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'user has been updated successfully.' });
    });
});
//  Delete user
app.delete('/delete-user', function (req, res) {
 
    let user_id = req.body.user_id;
 
    if (!user_id) {
        return res.status(400).send({ error: true, message: 'Please provide user_id' });
    }
    dbConn.query('DELETE FROM users WHERE id = ?', [user_id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'User has been updated successfully.' });
    });
}); 
// set port
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

Step 2 – Create New Angular App

Execute the following command on it to install angular app:

ng new my-new-app

Then execute the following command on terminal to install angular material:

ng add @angular/material

Step 3 – Create Components in Angular

Execute the following commands on 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

Step 4 – 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 { }

Step 5 – 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 { }

Step 6 – Create Angular Service for REST API Consumption

Create services in angular app; so go to app/service directory in Angular project and create User.ts class within.

Then, add the below code in app/service/User.ts file:

export class User {
    _id!: String;
    name!: String;
    email!: String;
}

Then, execute the command to create 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);
  }
}

Step 7 – 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>

Step 8 – 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>

Conclusion

Angular 12 CRUD application using Node.js, Express.js, and MySQL. In this tutorial, you have learned how to create crud app in angular 12 using nodejs and MySQL db with built REST API.

Recommended Angular Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *