menu

Questions & Answers

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?

Answers(1) :

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);
});
Comments:
2023-01-18 06:42:02
got an error: TypeError: _this.popupModal.showConfirmation(...).onClose is not a function
2023-01-18 06:42:02
can you try assigning value to some variable and debug like let x=this.popupModal.showConfirmation() then console.log(x) and see if you see onClose funtion there
2023-01-18 06:42:02
yes but it is inside __zone_symbol__value{onClose....}
2023-01-18 06:42:02
it should work can you create a stack blitz example for this