问题
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?
回答1:
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
});
来源:https://stackoverflow.com/questions/45922427/hook-to-bootstrap-4-modal-show-hide-events-from-typescript