Confirmation Modal Based on ngx-bootstrap/modal

One of the challenges when working with the Modal component from ngx-bootstrap is to how to capture button results in a generic way. For example, welldressedmen.net has multiple pages where a user deletes various items and I want to show a confirmation dialog before letting a user delete something.

Basically, we need to create a callback method off the initialState parameter and then use that method to communicate between components.

Here are the steps:

First, you need to setup ngx-bootstrap. Follow direction from their official site.

Then, create the “confirmation” Angular component:

 
import { Component, OnInit } from '@angular/core';
import { BsModalRef } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-confirm-modal',
  template: `<div class="modal-body text-center">
              <p>{{prompt}}</p>
              <button type="button" class="btn btn-primary" (click)="confirm()" >Yes</button>
              <button type="button" class="btn btn-primary" (click)="decline()" >No</button>
            </div>`
})
export class ConfirmModalComponent implements OnInit {

  constructor(public bsModalRef: BsModalRef) { }

  ngOnInit() {
  }

  confirm() {
    if (this.bsModalRef.content.callback != null){
      this.bsModalRef.content.callback('yes');
      this.bsModalRef.hide();
    }
  }

  decline() {
    if (this.bsModalRef.content.callback != null){
      this.bsModalRef.content.callback('no');
      this.bsModalRef.hide();
    }
  }
}

Then, you can use this component in other components that need to confirm user actions. For example:

import { BsModalService, BsModalRef, ModalOptions } from 'ngx-bootstrap/modal';
import { ConfirmModalComponent } from '../confirm-modal/confirm-modal.component';

@Component({
  selector: 'app-browser',
  templateUrl: './browser.component.html',
  styleUrls: ['./browser.component.css']
})
export class BrowserComponent implements OnInit {

  modalRef: BsModalRef;

  constructor(private modalService: BsModalService) { }

  ngOnInit() {
  }

  deleteRecord(recordId: string){

    this.modalRef = this.modalService.show(ConfirmModalComponent, {
      initialState: {
        prompt: 'Are you sure you want to delete this record?', 
        callback: (result) => {
          if (result == 'yes'){
            //pass recordId here
          }
        }
      }
    });
  }
}