Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook to bootstrap 4 modal show / hide events from Typescript

Having a modal with id myModal I'm trying to hook up to events when it shows and closes. Following the documentation of https://v4-alpha.getbootstrap.com/components/modal/#events I have added the following to my modal component:

this.modalElement = document.getElementById("myModal");
this.modalElement.addEventListener("hidden.bs.modal", this.onModalHidden);
this.modalElement.addEventListener("shown.bs.modal", this.onModalShown);

The event handlers for now will only console.log "shown" or "hidden" to test but unfortunately I can't get it to work:

private onModalShown = (event) => {
    console.log("modal is shown!!!");
}

Is there something missing and is it possible to achieve that?

like image 869
Carlos Torrecillas Avatar asked Dec 06 '25 09:12

Carlos Torrecillas


2 Answers

You can subscribe to onOpen and onDismiss events in ModalComponent.

@ViewChild('yourModal')
yourModal: ModalComponent;

I suggest you to subscribe to those events in ngAfterViewInit

ngAfterViewInit() {
 this.yourModal.onOpen.subscribe(() => {
   //do something
 });

 this.yourModal.onDismiss.subscribe(() => {
   //do something
 });
}
like image 123
Pathmila Kariyawasam Avatar answered Dec 07 '25 23:12

Pathmila Kariyawasam


You may try these code snippets:

First, I used ViewChild directive to call my modal.

    @ViewChild('MyModal') mymodal: ElementRef;

    //show
    $(this.mymodal.nativeElement).modal('show');
    //hide
    $(this.mymodal.nativeElement).modal('hide');

    //catch the event when modal is hidden
    //trigger implicity hide when backdrop is clicked or esc keypress
    // i had issues on closing modals and this fixed the problem
    $(this.mymodal.nativeElement).on('hidden.bs.modal',  () => {
        $(this).modal('hide');
        this.cancelProcedure();//my internal reset function
    });
like image 43
glennlosentes Avatar answered Dec 07 '25 22:12

glennlosentes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!