Bootstrap 模态 window 未关闭 angular 5 中的路线更改

Bootstrap modal window not closing on route change in angular 5

在我的 Angular 5 应用程序中使用 "@ng-bootstrap/ng-bootstrap": "1.0.0-beta.6" 版本时,一切看起来都很好。但是,如果我在模态 window 中有一个触发路线更改的按钮,即使在路线更改后模态 window 也不会关闭。

在我的小研究中,我发现在以前的 bootstrap 版本中点击模态 window 我们用来查看特定组件内的模态 window 相关代码以及路由随着组件被销毁而改变,甚至模态 window 也被销毁。但是在当前版本中,我几乎在 body 标签的末尾看到了模态 window 相关代码,它不受路由更改的影响。

有什么方法可以在路线更改时关闭模式吗?

尝试在父组件上定义 ngOnDestroy 并在路由更改时检查模式是否打开。

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

ngOnDestroy(){
 if(this.modalWindow !== null) this.modalWindow.close()
}

我已经更新了我的代码,以便能够从应用程序的任何地方处理模态 windows。

在组件中:

import {SharedService} from './shared.service.ts';
constructor(private _sharedService: SharedService) {}
this._sharedService.openModal(content);
ngOnDestroy() {
   this._sharedService.closeModal();
}

在共享服务中:

modalRef: any;
openModal(modalname) {
this.modalRef = this.modalService.open(modalname);
}
closeModal() {
   if (this.modalRef) {
       this.modalRef.close();
   }
}

ng-bootstrap 的第 4 版现在包含一个 dismissAll 方法来关闭所有打开的模式。它也可能存在于早至 3.1 的版本中,但我对此并不完全确定。

您可以在每次路由更改时从 app.component.ts 调用它,使用以下语法:

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

      }

    });

  }

}

如果您的组件中有模态 HTML,请在组件中试试这个。构造函数:

router.events.subscribe(val => {
  if (val) {
    $("#Model").modal("hide");
    $("#Model").hide();

  }
});

这是完整的代码

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  router: Router;
  modalService: NgbModal;

  constructor(router: Router, modalService: NgbModal) {
    this.router = router;
    this.modalService = modalService;
  }

  ngOnInit() {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        // close all open modals
        this.modalService.dismissAll();
      }
    });
  }

}

另一种选择。在父级上,在其 constructor:

中声明模态服务
constructor(private modalService: NgbModal) { }

接下来,在 ngOnDestroy 上,您关闭所有模态框:

ngOnDestroy() {
    this.modalService.dismissAll();
}

这样,如果有任何遗漏,您就不会从另一个组件中签入 ngOnInit