Search code examples
angularngx-bootstrap

ngx-bootrap - On Hide event not firing


I have a modal from ngx-bootstrap and when closed I want to trigger a function in my angular component. But no matter how I try to catch the event I can't.

Event I want to fire is straight forward - I just want to see it in the console for now:

// Reset the user data
clearUserData() {
  console.log('Data Cleared');
}

Approach one - using the modal template directly:

<ng-template #template bsModal (onHide)="clearUserData()">
...
</ng-template>

Result: Nothing happens - so console log and no error message

Approach two: Using the modal service:

// Open Progress Modal
buyNow(template: TemplateRef<any>) {
  // Open the model
  this.modalRef = this.modalService.show(template);
  this.modalRef.content.onClose.subscribe(result => {
    console.log('results', result);
  });
}

Result: This give me an error message in the console: TypeError: Cannot read properties of null (reading 'onClose')


Solution

  • I have come across this stackoverflow answer. The accepted answer and Bartando's answer as well. So the idea is to use the modalService and there is a dismiss reason property that they have put and then inside you can call your clearUserData()

    That's how this goes

    this.modalService.setDismissReason(theReason);
    

    I am sharing the reference link as well. SO's LINK