How to Make Angular CRUD Operation with JSON-Server

Hello Friends Welcome to M-SoftTech. In Today Article I will l teach you. how to make CRUD Operation Using JSON-Server. I will explain you step by step.

First Step You need to Install JSON-Server I will share the download link with you.

https://www.npmjs.com/package/json-server

Start JSON Server

json-server –watch db.json

This is your API URL

http://localhost:3000/user

I have used bootstrap for designing you can add bootstrap library in your index.html file. I will share the link with you.

Here is the bootstrap CDN File Link

Index.html

    <!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>  
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

For Notification Alert I have used Ngx-Toastr I will share the link in below

https://www.npmjs.com/package/ngx-toastr

First step you will install this ngx-toastr and then you have add CSS file in your angular JSON file. Because if you don’t add this file. you find your ngx-toastr not working properly.

First Step you need to create a user component. and then your create a service file. and then you need to import ReativeFormsModule in your app module file. and HttpClientModule and ToastrModule

App.Module.ts

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { ToastrModule } from 'ngx-toastr';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UserComponent } from './user/user.component';


@NgModule({
  declarations: [
    AppComponent,
    UserComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    ToastrModule.forRoot({
      closeButton:true,
      timeOut:5000,
      progressBar:true
    })
    
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

User.component.html

<header>
    <div class="container">
        <div class="row">
        <div class="col-sm-6">
           <h2>USER</h2> 
        </div>
        <div class="col-sm-6" >
            <button class="btn btn-light" style="float: right;" data-bs-toggle="modal" data-bs-target="#exampleModal" (click)="addmodel()">Add User</button>
        </div>
    </div>
    </div>
</header>
<br/><br>

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <table>
                <tr>
                    <th>Id</th>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Website</th>
                    <th>Action</th>
                </tr>
                <tr *ngFor="let user of data; let i = index;">
                    <td>{{i+1}}</td>
                    <td>{{user.name}}</td>
                    <td>{{user.email}}</td>
                    <td>{{user.phone}}</td>
                    <td>{{user.website}}</td>
                    <td>
                        <button class="btn btn-primary" data-bs-toggle="modal" (click)="edit(i, user)" data-bs-target="#exampleModal"><i class="fa fa-edit"></i></button>
                        <button class="btn btn-danger" style="margin-left: 20px;" (click)="delete(i, user)"><i class="fa fa-trash"></i></button>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="exampleModal" 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">{{isedit ? 'Edit User Details' : 'Add User'}}</h5>
                <span data-bs-dismiss="modal" aria-label="class" class="close-btn1">x</span>
            </div>

            <div class="modal-body">
                <div class="form-box">
                    <form [formGroup]="userform" (ngSubmit)="isedit ? update(userform) : sendata(userform)">

                        <div class="form-group">
                            <label>Name</label>
                            <input type="text" placeholder="Name" formControlName="name" class="form-control mt-3 mb-3"/>
                        </div>

                        <div class="form-group">
                            <label>Email</label>
                            <input type="text" placeholder="Email" formControlName="email" class="form-control mt-3 mb-3"/>
                        </div>

                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" placeholder="Phone" formControlName="phone" class="form-control mt-3 mb-3"/>
                        </div>

                        <div class="form-group">
                            <label>Website</label>
                            <input type="text" placeholder="Name" formControlName="website" class="form-control mt-3 mb-3"/>
                        </div>
                        <button type="submit" class="btn btn-primary" data-bs-dismiss="modal">{{isedit ? 'UPDATE' : 'SUMBIT'}}</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

user.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { DataserviceService } from '../dataservice.service';


@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent {
  userform:FormGroup|any;
  data:any;
  isedit:boolean=false;
  username:any;
  usernameShow:any;

 
  constructor(private _dataservice:DataserviceService, private _toast:ToastrService) { }

  ngOnInit(): void {
   this.userform = new FormGroup({
    'name':new FormControl(),
    'email':new FormControl(),
    'phone':new FormControl(),
    'website':new FormControl()
   })
   this.getdata();
  }
  update(user:any){
    this.userform.id = user.id;
    this.usernameShow= this.userform.value.name;
    this._dataservice.update(this.userform.id, this.userform.value).subscribe(res=>{
      this.showInfo();
      this.getdata();
    })

  }
  sendata(userform:FormGroup){
    this.data.push(this.userform.value);
    this.username= this.userform.value.name;
    this._dataservice.postdata(this.userform.value).subscribe(res=>{
      this.showSuccess();
      this.getdata();
    })
  }

  getdata(){
    this._dataservice.getdata().subscribe(res=>{
      this.data = res;
    })
  }
  
  addmodel(){
    this.isedit=false;
    this.userform.reset();
  }

  edit(i:any, user:any){
    this.isedit=true;
    this.userform.id= user.id;
    this.userform.setValue({
      name:user.name,
      email:user.email,
      phone:user.phone,
      website:user.website
    })
  }

  delete(index:number, user:any){
    this.userform.id= user.id;
    this._dataservice.delete(this.userform.id, user).subscribe(res=>{
      this.data.splice(index, 1);
      this.showError();
    })
  }

  



    public showSuccess():void{
      this._toast.success('User Data Successfully Added', this.username);
    }

    public showInfo():void{
      this._toast.info('Data Has Successfully Updated', this.usernameShow)
    }

    public showError():void{
      this._toast.error('Data Has Deleted');
    }
  
}

user.component.css

header{
    background-color: #5582e4;
    padding: 25px;
}
h2{color: white;}

Style.css

.form-box{
    padding: 25px;
    background-color: #bcbcbc3d;
    margin: 0px auto;
}
h4{
    text-align: center;
}
.modal-body{
    margin: -18px;
}
table{
    border-collapse: collapse;
    width: 100%;
    text-align: center;
}
th, td{
    text-align: center;
    padding: 8px;
}
tr:nth-child(even){
    background-color: #f2f2f2;
}
th{
    background-color: #5582e4;
    color: white;
}
.modal-header{
    background-color: #5582e4;
    color: white;
}
.close-btn1{
    font-family:Arial, Helvetica, sans-serif;
    background-color: white;
    padding: 6px 12px;
    font-weight: bold;
    border-radius: 23px;
    color:#5582e4;
    cursor: pointer;
}

DataService.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataserviceService {

apiurl="http://localhost:3000/user"; 

constructor(private _http:HttpClient){}

getdata(){
  return this._http.get(this.apiurl);
}

postdata(user:any){
  return this._http.post(this.apiurl, user)
}

update(id:any, user:any){
  return this._http.put(`${this.apiurl}/${id}`, user)
}

delete(id:any, user:any){
  return this._http.delete(`${this.apiurl}/${id}`, user)
}
  
}

If you enjoyed reading this post and have found it useful for you, then please give a share with your friends, and follow me to get updates on my upcoming posts. 

if you have any confusion Comment below or you can contact us by filling out our contact us.

YOU MIGHT ALSO LIKE

How To Create A Website Using HTML And CSS Step By Step Website Tutorial

How to make a dashboard Design Using html CSS

If you have any problem to understand this code you can watch also video tutorial

Leave a Reply

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