Search code examples
angularbootstrap-modalangular14

How to wait for bootstrap modal response in angular 13?


I am new to angular and trying to call a bootstrap modal and wait for its response, Everything is working, except it is not returning any value:

PS: I am using bootstrap5 CDN version

This is my bootstrap.component.ts:

  showConfirmation() {
    this.confirmationModal.show();
  }


  closeConfirmation() {
    this.confirmationModal.hide();
  }

  confirmationOk(): boolean {
    this.confirmationModal.hide();
    return true;
  }

  confirmationDeclined(): boolean {
    this.confirmationModal.hide();
    return false;
  }

my bootstrap.component.html:

<button type="button" class="btn btn-secondary radius-none" (click)="confirmationOk()">Yes</button>
          <button type="button" class="btn btn-primary radius-none" (click)="confirmationDeclined()">No</button>

and my parent.component.ts:

 let x = await this.popupModal.showConfirmation()
 console.log(x) //-------No value here

I just want to call this.popupModal.showConfirmation() and then wait for the confirmation button to be click and get the response value. Is there a way to achieve it?


Solution

  • You can try defining an observable in your modal component and return observable when you open the modal and subscribe in the parent component. So in your bootstrap.component.ts

      _onClose:Subject<any>=new Subject<any>();
    
      showConfirmation() {
        this.confirmationModal.show();
        retrun {
         onClose:()=>this._onClose;
        }
      }
    
    
      closeConfirmation() {
        this.confirmationModal.hide();
        this._onClose.next(false);
      }
    
      confirmationOk(): boolean {
        this.confirmationModal.hide();
        this._onClose.next(true);
      }
    
      confirmationDeclined(): boolean {
        this.confirmationModal.hide();
        this._onClose.next(false);
      }
    

    then in your parent component

    this.popupModal.showConfirmation().onClose().subscribe(value=> {
      console.log(value);
    });