angular - 如何从另一个组件打开 ng bootstrap modals?

标签 angular ng-bootstrap

我想在组件 1 的帮助下从另一个模块打开或关闭模态。但是目前我无法访问该组件中模态的 ngBootstrap 的 modalRef,以便我可以关闭/打开它。

假设这个场景

一个模块

<component1></component1>

另一个模块 这个模块有多个组件,每个组件都有模态,我需要根据组件 1 的条件显示或隐藏。

<component2> //have ng bootstrap modal in it </component2>
<component3> //have ng bootstrap modal in it </component3>
<component4> //have ng bootstrap modal in it </component4>
<component5> //have ng bootstrap modal in it </component5>
<component6> //have ng bootstrap modal in it </component6>

目前我只是通过在该模块中放置一个隐藏按钮并使用来自另一个组件的 JavaScript 单击它来实现这一点,我知道这不是一个好方法所以我希望有人给我一些调用这些模态的方法或告诉我设计是否有任何更改。

据我所知,我认为服务会很好地做到这一点。但在改变设计之前,我想听听别人的意见。谢谢

最佳答案

我刚刚遇到了同样的问题并发现了这个线程,Aniruddha Das 在强调基本要求方面做得很好,但我发现它错过了 TemplateRef 用法,它是接下来,以防万一其他人有这个问题,我会完成它。使用与 Aniruddha 相同的模型

模板:

<ng-template #updatemodal>
  <div class="modal">
    stuff here...
  </div>
</ng-template>

组件:

@ViewChild('updatemodal')
private modalRef: TemplateRef<any>;

private myModal<any>;

constructor(SomeService: SomeService, modalService: NgbModal){
  this.SomeService.popup.subscribe((val)=>{
     if(val === 'open') {
       this.myModal = this.modalService.open(this.modalRef);
     }
   });
}

引用已创建的模态是在响应中允许更多使用和灵 active 的好方法,并使用:

this.myModal.result.then((result) =>{
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });

来自 NgBootstrap网站

关于angular - 如何从另一个组件打开 ng bootstrap modals?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792291/

相关文章:

javascript - 在 Ionic 2 上动态更新标签徽章

angular - 在 Angular4 中使用网络套接字?

angular - 指令 QuillEditorBase 中的 Ngx-Quill 错误

angular - 加载 ngb-Carousel 时跳转到最后一张幻灯片

css - 覆盖组件 HTML/在第三方组件上添加或删除 css

css - 按钮垂直组,在 bootstrap 4 中对齐到底部

node.js - 组件之间的 Angular 4 ngModel

angular-cli - 什么是 npm i bootstrap@next?

angular - 使用 ng-bootstrap 在模态中提交表单

angular - ionic 2 cordova,安装 cordova 插件类型