gmail 777
gmail 777

Reputation: 23

Call a function on bootstrap modal close(Both through escape button and any other way) in angular

I am working with angular. I have Bootstrap modal popup. I have called a function when its gets closed. But the problem is there are other ways to close like pressing escape button or simply clicking on the screen. I don't know how to call the same function when these events like escape occur? I have googled stackoverflow and couldn't find a proper solution.

Stackblitz

Upvotes: 1

Views: 1185

Answers (3)

StackOverwhelmed
StackOverwhelmed

Reputation: 1

I ran into the same problem using Angular Bootstrap. I created the initial code for my modal by referencing the Modal with options documentation.

The NgbModalOptions has a beforeDismiss option that you can use to pass a callback function that will run before the modal closes. I used it like this to clear data before the modal is closed:

// my-component.component.html

<ng-template #modalTemplate let-modal>
  ...
</ng-template>

<button
  type="button"
  (click)="openModal(modalTemplate)"
>
  Open Modal
</button>
// my-component.component.ts

openDialog(modalTemplate) {
  this.modalService.open(modalTemplate, { size: 'lg', beforeDismiss: () => {
      this.clearModalData();
      return true;
    },
  });
}

I hope that helps! I use Angular at work, but if you are looking for a simple JavaScript framework that gets out of your way and lets you be productive, then may I suggest Svelte.js (specifically the SvelteKit framework). It is awesome! Good luck!

Upvotes: 0

Rohit Khandelwal
Rohit Khandelwal

Reputation: 632

You can use the blur event of your modal element. And onBlur do whatever you want to.

Upvotes: 0

Milad Esrafilian
Milad Esrafilian

Reputation: 173

You can add an even listener on hide.bs.modal event. This even fires immediately when the hide instance method has been called. You can see more detail in the docs

Upvotes: 1

Related Questions