【问题标题】:Open ng-bootstrap modal programmatically以编程方式打开 ng-bootstrap 模式
【发布时间】:2017-12-21 08:09:34
【问题描述】:

我有一个 Angular 4 页面,包括一个 ng-bootstrap 模式。我的代码如下所示。

foo.html

[...]
<button class="btn btn-sm btn-secondary material-icons"
(click)="open(content)">search</button>

<ng-template #content let-c="close" let-d="dismiss">
    content in here
</ng-template>
[...]

foo.ts

[...]
constructor(private modalService: NgbModal) { }
[...]
open(content) {
   let options: NgbModalOptions = {
     size: 'lg'
   };

   this.modalService.open(content, options);
}
[...]

现在,当我单击按钮时,模式会打开。我现在要做的是在 ngChanges 上打开模型。

ngOnChanges(changes: any) {
   open(content)
}

我的问题是:如何在这里获取“内容”?有没有办法以编程方式获取 ng-template?提前致谢!

【问题讨论】:

    标签: angular typescript modal-dialog ng-bootstrap ng-template


    【解决方案1】:

    要访问类中的content 元素,请声明:

    @ViewChild('content', { static: false }) private content;
                             ^for Angular8+
    

    并在类的顶部添加相应的导入:

    import { ViewChild } from '@angular/core';
    

    最后在更改检测时为该元素调用 open 方法:

    ngOnChanges(changes: any) {
       this.open(this.content);
    }
    

    【讨论】:

      【解决方案2】:

      从 Angular 8 开始,您还应该在 ViewChild 中传递静态选项:{static: false}

      import { ViewChild } from '@angular/core';
      
      @ViewChild('content', { static: false }) private content;
      
      constructor(private modalService: NgbModal) { }
      
      this.modalService.open(this.content);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-13
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        • 2014-05-15
        相关资源
        最近更新 更多