Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngbModal as a generic Confrimation Box

I am trying to create generic confirmation box using ngbmodal, which will be used across the App. In which, Title and message will be passed to the modal from the calling component. I created as a DialogService and added in the entryComponents. Now I am able to show the Confirmation box. But not able to get the result. Below is the code to show the ConfirmationBox component. How to get the value from it

    const modalRef = this.modalService.open(ConfirmationBoxComponent,{backdrop:"static"})
    modalRef.componentInstance.name = "Message";
    modalRef.componentInstance.confirmationBoxTitle = "Confirmation?"
    modalRef.componentInstance.confirmationmessage = "Do you want to cancel?"
    modalRef.componentInstance.changeRef.markForCheck();
like image 267
Vairavan Avatar asked Apr 25 '17 13:04

Vairavan


1 Answers

There are many easy ways of achieving this but I would suggest one that is the simplest and the most effective IMO: resolve modal's result promise with the user's choice. This is as simple as doing following in the component representing modal's content (notice activeModal.close(...)):

<button (click)="activeModal.close(true)">Yes</button>
<button (click)="activeModal.close(false)">No</button>

Afterwards you can get back user's answer from the result promise of the NgbModalRef (notice modalRef.result.then):

open() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.confirmationBoxTitle = 'Confirmation?';
    modalRef.componentInstance.confirmationMessage = 'Do you want to cancel?';

    modalRef.result.then((userResponse) => {
      console.log(`User's choice: ${userResponse}`)
    });        
  }

You can see all this in action in the following plunker: http://plnkr.co/edit/yYIx1m1e2nfK0nxFwYLJ?p=preview

like image 61
pkozlowski.opensource Avatar answered Oct 15 '22 01:10

pkozlowski.opensource