Angular – How to create a Modal Dialog

By | 20/11/2019

In this post, we will see how to create a Modal Dialog in an Angular project.
In detail, we will create a modal dialog in order to delete a single item in the Users list of our usual project.

First of all, we open the file app.module.ts and we import the module ModalModule, in order to use the Modal Dialog of ngx-bootstrap:

import { ModalModule } from 'ngx-bootstrap';
..
..
..
],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    FormsModule,
    ModalModule.forRoot()
  ],
..
..



Now, we open the file webapiuser.service.ts and we add the method that we will use to delete the User:

  deleteUser(idUser: number){
    return this.http.delete(this.webapiUserUrl +"/user/"+ idUser);
  } 



The last files to modify are:

[LISTENERS.COMPONENT.HTML]

<p>List of Users</p>
<table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Id</th>
        <th scope="col">Username</th>
        <th scope="col">TypeUser</th>
        <th scope="col">Create Date</th>
        <th scope="col">Delete User</th>
      </tr>
    </thead>
    <tbody *ngFor="let item of lstUsers; index as i"> 
      <tr>
        <td>{{i+1}}</td>
        <td>{{item.id}}</td>
        <td>{{item.username}}</td>
        <td>{{item.typeUserName}}</td>
        <td>{{item.createDate}}</td>
        <td><button type="button" class="btn btn-primary" (click)="openModal(template, item.username, item.id)">Delete</button></td>
      </tr>
    </tbody>
  </table>


<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Modal</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    <p>Do you want to delete {{userToDelete}}?</p>
    <button type="button" class="btn btn-primary" (click)="confirm()" >Yes</button>
    <button type="button" class="btn btn-default" (click)="decline()" >No</button>
  </div>
</ng-template>



and

[LISTENERS.COMPONENT.TS]

import { Component, OnInit, TemplateRef } from '@angular/core';
import { User } from '../user';
import { WebapiuserService } from '../webapiuser.service';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-listusers',
  templateUrl: './listusers.component.html',
  styleUrls: ['./listusers.component.css']
})
export class ListusersComponent implements OnInit {
  // define an Array of User
  lstUsers: Array<User>;
  modalRef: BsModalRef;
  userToDelete: string;
  userIdToDelete: number;

  // Use the dependency injection to use the service in this component
  constructor(private serviceuser: WebapiuserService, private modalService: BsModalService) { }

  ngOnInit() {
    
    // call the service to take the list of users
    this.serviceuser.getListUsers().subscribe(data => {
      this.lstUsers = data;
    });
  }

  // method used to show the modal dialog
  openModal(template: TemplateRef<any>, username, id) {
    this.userToDelete = username;
    this.userIdToDelete = id;
    this.modalRef = this.modalService.show(template, {class: 'modal-sm'});
  }

  // method used to call the service for deleting User
  confirm(): void {
    this.modalRef.hide();
    // call the service
    this.serviceuser.deleteUser(this.userIdToDelete)
    .subscribe(
      // if it's ok, call the method newUserOk
      data => this.deleteOk(),
      error => console.log("Error", error)
    )
  }

  deleteOk()
  {
    // we will show a message 
    alert("The user " + this.userToDelete + "was deleted!");
    // and go to the List Users page
    this.ngOnInit();
  }

  // close the modal dialog
  decline(): void {
    this.modalRef.hide();
  }
}



In order to verify that new form works fine, we run (with the command ng serve) the application and we try to delete an user:



Leave a Reply

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