2

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?

Carlos Torrecillas
  • 4,965
  • 7
  • 38
  • 69
  • 1
    I think it's better for you to use bootstrap for angular - https://ng-bootstrap.github.io/#/home – baklazan Aug 28 '17 at 15:27
  • do you have open and close button for the modal ? then you can hook up using button clicks . Are you not able to hook a bootstrap modal to angular ts ? If you are looking to hook up a modal to angular using only bootstrap check this https://stackoverflow.com/a/45387777/2708210 – Rahul Singh Aug 28 '17 at 15:29
  • I could use NgB but I wanted to stick to the original bootstrap if that was possible. I don't really have a close button because it's an image that is displayed in the modal (maybe is not the best thing to do but I thought it could work) – Carlos Torrecillas Aug 28 '17 at 15:35
  • 1
    Well there are a lot of reasons why this is a bad practice... Don't do unecessary direct calls to the DOM elements.http://angularjs.blogspot.fr/2016/04/5-rookie-mistakes-to-avoid-with-angular.html – Alex Beugnet Aug 28 '17 at 15:48

2 Answers2

7

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
 });
}
2

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
    });
  • 1
    This was a great start, just missing that this needs to be wrapped in an AfterViewInit in order for it to work. – QT Ray Dec 06 '19 at 21:17