Search code examples
bootstrap-modalangular5ng-bootstrap

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?


Solution

  • 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();        
    
          }
    
        });
    
      }
    
    }