Pages

A complete guide to Perform crud operation in angular using modal popup

We add a class model with a shared folder with the following command.

ng g class shared/user --type=model



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;

}


Add 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, add userdetail components

ng g c userdetail




Note:

g - generate

c - component

s - service


Adding Bootstrap

Now, go 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>


Now, we open app.module.ts to register services and module. In app.module, we have all the components has been auto added. But, we need to add service so we can use them in our angular app. Also we need to add 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:



No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...