Question:
A complete guide for CRUD operation in Angular using model popup

This blog will help you perform a CRUD operation in Angular using a model popup. Read our blog, If you want to create a >backend for CRUD app using NodeJS, ExpressJS, and MongoDB.


Step 1: Type the following command and add a class model with a shared folder


ng g class shared/user --type=model


Step 2: Now add property to the user.model.ts


export class User {

    id:number= 0;

    name!: string;

    lastName:string='';

    email:string = '';

    age!:number;

    gender:string='Male';

    isActive!:number;

}


Step 3: After this, services and components: 


  1. Services

We will add a service that will communicate with a Web API inside the shared folder.

n g s shared/user

  1. Components

Now that you have added services, add user detail components

ng g c userdetail

Note:

g - generate

c - component

s - service

Adding Bootstrap

Now, navigate to> https://getbootstrap.com/docs/4.0/getting-started/introduction/ and copy the plugin of java script and CSS in index.html


<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angularcrudoperation</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <link rel="preconnect" href="https://fonts.gstatic.com">

  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body class="mat-typography">

  <app-root></app-root>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>

  <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

</body>

</html>


To register services and modules, we now open app.module.ts. We have all the components automatically added to the app.module. However, to use them in our angular app, we must add a service. We must also include the HTTP module.


import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import {HttpClientModule} from '@angular/common/http'

import { FormsModule } from '@angular/forms';

 

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import {MatTableModule} from '@angular/material/table'

import { MatSortModule } from '@angular/material/sort';

import {MatPaginatorModule} from '@angular/material/paginator';

import { UserComponent } from './user/user.component';

import {MatTableDataSource} from '@angular/material/table';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { UserdetailComponent } from './userdetail/userdetail.component';

@NgModule({

  declarations: [

    AppComponent,

    UserComponent,

    UserdetailComponent,

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    MatTableModule,

    MatSortModule,

    MatPaginatorModule,

    BrowserAnimationsModule,

    HttpClientModule,

    FormsModule

  ],

  schemas:[CUSTOM_ELEMENTS_SCHEMA],

  providers: [],

  bootstrap: [AppComponent]

})

export class AppModule { }

Adding services and components code:-

  1. Service

Now, Open user.service.ts file and add code.

import { Injectable } from '@angular/core';

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

import { User } from './user.model';

import { Observable } from 'rxjs';

@Injectable({

  providedIn: 'root'

})

export class UserService {

  constructor(private myhttp:HttpClient) { }

  userUrl:string ='https://localhost:44395/api/Customer/TblCustomer';

  userPostUrl:string ='https://localhost:44395/api/Customer/PostCustomer';

  userDeleteUrl = 'https://localhost:44395/api/Customer/DeleteCustomer';

  userPutUrl = 'https://localhost:44395/api/Customer/UpdateCus';

  listuser : User[] = [];

  userdata : User = new User(); // for post data // insert data

  saveUser()

  {

    //  console.log("postapi",this.customerdata.imgfile);

    return this.myhttp.post(this.userPostUrl,this.userdata);

  }

  updateUser()

  {

    return this.myhttp.post(this.userPutUrl,this.userdata);

  }

  getUser(): Observable<User[]>

  {

    return this.myhttp.get<User[]>(this.userUrl);

  }

  deleteUser(id:number)

  {

    return this.myhttp.delete(`${this.userDeleteUrl}/${id}`);

  }

}

Now, Open userdetail.component.ts file and add code.

import { Component, OnInit } from '@angular/core';

import { User } from '../shared/user.model';

import { UserService } from '../shared/user.service';

import { NgForm } from '@angular/forms';

@Component({

  selector: 'app-userdetail',

  templateUrl: './userdetail.component.html',

  styleUrls: ['./userdetail.component.css']

})

export class UserdetailComponent implements OnInit {

  constructor(public userService:UserService) { }

  displayStyle = "none";

  openPopup() {

    this.displayStyle = "block";

  }

  closePopup() {

    this.displayStyle = "none";

  }

  ngOnInit() {

    this.userService.getUser().subscribe(data=>{

      this.userService.listuser=data

    });

  }

  populateUser(selectedUser:User)

  {

    this.displayStyle = "block";

    this.userService.userdata=selectedUser;

  }

  delete(id:number)

  {

    if(confirm('Are you really want to delete this record?'))

    {

      this.userService.deleteUser(id).subscribe(data=>{

        console.log('Record delete');

        this.userService.getUser().subscribe(data=>{

          this.userService.listuser=data

        });

      },

      err=>{

        console.log('Error not deleted');

      });

    }

  }

  submit(form: NgForm) {

    this.userService.userdata.isActive = form.value.isActive == true ? 1 : 0;

    if (this.userService.userdata.id == 0) {

      this.insertCustomer(form);

    }

    else {

      this.updateCustomer(form);

    }

  }

  insertCustomer(myForm: NgForm) {

    this.userService.saveUser().subscribe(d => {

      this.resetForm(myForm);

      this.refreshData(myForm);

      console.log('saved success');

    });

  }

  updateCustomer(myForm: NgForm) {

    this.userService.updateUser().subscribe(d => {

      this.resetForm(myForm);

      this.refreshData(myForm);

      console.log('update success');

    })

  }

  resetForm(myForm: NgForm) {

    myForm.form.reset();

    this.userService.userdata = new User();

  }

  refreshData(myForm: NgForm) {

    this.userService.getUser().subscribe(res => {

      this.userService.listuser = res;

    });

  }

}

  1. Components (userdetail)

 

Now, Open the app.component.html and add app-user-details selector 

Now, Open the userdetail.component.html and add code.

    <button

      style="margin: 100px; padding: 10px"

      type="button"

      class="btn btn-primary"

      (click)="openPopup()">Add User

    </button>

    <div

      class="modal"

      tabindex="-1"

      role="dialog"

      [ngStyle]="{'display':displayStyle}">

      <div class="modal-dialog" role="document">

        <div class="modal-content">

          <div class="modal-header">

            <h4 class="modal-title">User Form</h4>

          </div>

          <div class="modal-body">

            <div class="container">

            </div>

            <div class="formAdd">

            <form autocomplete="off" #myForm="ngForm" (ngSubmit)="myForm.form.valid && submit(myForm)">

                <div class="container">

                    <div class="row">

                        <div class="col-md-3">

                            <input type="hidden" name="id" [value]="userService.userdata.id">

                            <label for="name">Name</label>

                            <input type="text" class="form-control" name="name" placeholder="name" #name="ngModel" [(ngModel)] ="userService.userdata.name">

                        </div>

                        <div class="col-md-3">

                            <label for="lastname">Last Name</label>

                            <input type="text" class="form-control" name="lastname" placeholder="lastname" #lastname="ngModel" [(ngModel)] ="userService.userdata.lastName">

                        </div>

                        <div class="col-md-3">

                            <label for="email">Email</label>

                            <input type="email" class="form-control" name="email" placeholder="email" #email="ngModel" [(ngModel)] ="userService.userdata.email">

                        </div>

                        <div class="col-md-3">

                            <label for="age">Age</label>

                            <input type="number" class="form-control" name="age" placeholder="age" #age="ngModel" [(ngModel)] ="userService.userdata.age">

                        </div>

                    </div>

                        <div class="row mt-2">

                        <div class="col-md-6">

                            <label for="gender">Gender</label>

                            <div class="row">

                                <div class="col-md-6">

                                    <div class="form-check-inline">

                                        <label class="form-check-label">

                                          <input type="radio"  class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="userService.userdata.gender" value="Male">Male

                                        </label>

                                      </div>

                                      <div class="form-check-inline">

                                        <label class="form-check-label">

                                            <input type="radio" class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="userService.userdata.gender" value="Female">Female

                                        </label>

                                      </div>

                                     

                                </div>

                            </div>

                        </div>

                        </div>

                    <div class="row">

                        <div class="col-md-10"></div>

                        <div class="col-md-2">

                            <button type="submit" class="btn btn-Success">Save</button>

                        </div>

                    </div>

                </div>

            </form>

            </div>

     

          </div>

          <div class="modal-footer">

            <button type="button" class="btn btn-danger"

                    (click)="closePopup()">

              Close

            </button>

          </div>

        </div>

      </div>

    </div>

<div class="container">

    <app-customer-form></app-customer-form>

    </div>

    <table class="table table-hover">

        <thead class="thead-dark">

            <tr>

                <th>Name</th>

                <th>Last Name</th>

                <th>Email</th>

                <th>Age</th>

                <th>Gender</th>

                <th>Action</th>

            </tr>

        </thead>

        <tbody>

            <tr *ngFor="let us of userService.listuser">

                <td>{{us.name}}</td>

                <td>{{us.lastName}}</td>

                <td>{{us.email}}</td>

                <td>{{us.age}}</td>

                <td>{{us.gender}}</td>

                <td>

                    <div class="dropdown">

                        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">

                          Action

                        </button>

                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">

                          <a class="dropdown-item" href="#" (click)="populateUser(us)">Edit</a>

                          <a class="dropdown-item" href="#" (click)="delete(us.id)">Delete</a>

                        </div>

                      </div>

                </td>

            </tr>

        </tbody>

    </table>

Now , add the CSS to the app.component.css

table {

    width: 100%;

  }

  .mat-mdc-form-field {

    font-size: 14px;

    width: 100%;

  }

  td, th {

    width: 75px;

  }

  section {

    display: table;

  }

  .example-label {

    display: table-cell;

    font-size: 14px;

    margin-left: 8px;

    min-width: 60px;

  }

  .example-button-row {

    display: table-cell;

    max-width: 300px;

  }

  .example-button-row .mat-mdc-button-base {

    margin: 8px 8px 8px 0;

  }

  .example-flex-container {

    display: flex;

    justify-content: space-between;

    flex-wrap: wrap;

  }

  .example-button-container {

    display: flex;

    justify-content: center;

    width: 120px;

  }

Now, run the project using the below command:

"ng serve -o" or "ng serve --open"

User Details:

Add user:

Edit user:

User detail after editing:

Delete user:


Suggested blogs:

>Create a One Page App with Angular.js, Node.js and MongoDB

>Create a basic Web Application with Angular

>How to add number together and despite using parseFloat I still get NaN

>Ionic 6 AppState change causing duplicate subscription results

>How to Focus shifting between array of standard <input> controls?

>Mat Paginator not working for Mat table in Angular

>How can I filter operator in rxjs and subscribe in Angular


Adequate Infosoft

Adequate Infosoft

Submit
0 Answers