Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal window not closing on route change in angular 5

On using the "@ng-bootstrap/ng-bootstrap": "1.0.0-beta.6" version in my Angular 5 application, everything looks fine. But if I have a button in the modal window which triggers route change, the modal window is not closed even after the route change.

On my little research, I found something in previous bootstrap versions on click of the modal window we use to see the modal window related code inside the specific component and on route change as the component gets destroyed, even the modal window use to be destroyed. But in the current version, I am seeing the modal window-related code almost at the end of the body tag which doesn't get affected with route change.

Is there any way to close the modal on route change?

like image 597
Anonymous Avatar asked Jan 11 '18 05:01

Anonymous


2 Answers

Version 4 of ng-bootstrap now includes a dismissAll method that closes all open modals. It may also be present in versions as early as 3.1, but I'm not completely sure about that.

You can call it from app.component.ts on every route change, using this syntax:

import { Router, NavigationEnd } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

export class AppComponent {

  constructor(router: Router, modalService: NgbModal) { }

  ngOnInit() 
  {

    this.router.events.subscribe(event => {

      if (event instanceof NavigationEnd) {

        // close all open modals
        this.modalService.dismissAll();        

      }

    });

  }

}
like image 196
Derrick Miller Avatar answered Nov 08 '22 22:11

Derrick Miller


Try to define ngOnDestroy on your parent component and check if modal is open or not when route change.

modalWindow = null;
openModal(){
 this.modalWindow.open('YourComponent')
}

ngOnDestroy(){
 if(this.modalWindow !== null) this.modalWindow.close()
}
like image 45
Oleksandr Oleksiv Avatar answered Nov 09 '22 00:11

Oleksandr Oleksiv