20

我有一个 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>
[...]

脚.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?提前致谢!

4

2 回答 2

39

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

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

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

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

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

ngOnChanges(changes: any) {
   this.open(this.content);
}
于 2017-07-16T22:02:16.883 回答
1

从 Angular 8 你还应该传递静态选项:{static: false}在 ViewChild

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

@ViewChild('content', { static: false }) private content;

constructor(private modalService: NgbModal) { }

this.modalService.open(this.content);
于 2020-08-06T11:32:46.387 回答