angular - ViewChild 返回“未定义”-Angular2
问题描述
我正在尝试通过在父组件上按下按钮来执行子组件的功能,但由于某种原因它未定义。
家长:
.. com1.html
<ng-template #content let-c="close" let-d="dismiss">
<div class="modal-header">
<h4 class="modal-title">Title</h4>
</div>
<div class="modal-body" style="display: flex; justify-content: center;">
<app-com2 [var1]="value" #traceRef></app-com2>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="savePNG()"><i class="fa fa-download"></i>PNG</button>
<button type="button" class="btn btn-outline-dark" (click)="c()">Close</button>
</div>
</ng-template>
<button class="btn btn-sm btn-secondary" (click)="open(content)">Button</button>
...com1.ts
export class com1 implements OnInit {
@ViewChild('traceRef') traceRef;
value = "something";
constructor(private modalService: NgbModal) {}
savePNG() {
this.traceRef.savePNG();
}
open(content: any) {
this.modalService.open(content, { windowClass: 'temp-modal' });
}
}
谁能指出我正确的方向,因为其他线程没有帮助:(即使使用 ngAfterViewInit 它仍然未定义。
解决方案
它无法正常工作的原因ng-template
是NgbModal
服务创建模板并且不将其附加到父视图而是附加到根ApplicationRef
const viewRef = content.createEmbeddedView(context);
this._applicationRef.attachView(viewRef);
这意味着您的查询对于您的组件将始终不脏。
在常见情况下(参见@ConnorsFan提供的示例),我们使用vcRef.createEmbeddedView
它负责检查父视图中的查询:
vcRef.createEmbeddedView
||
\/
function attachEmbeddedView(
...
Services.dirtyParentQueries(view); <========== set dirty for queries
我在这里看到的简单解决方案是直接在模板中传递或调用引用:
(click)="traceRef.savePNG()"
推荐阅读
- sql - MS Access - SQL Inner Join 两个条件和 Len-Function
- git - 在 Mac 中将 Visual Studio Code 与 Git 关联
- angular - 如何处理具有严重可观察属性的可观察对象?
- node.js - 在代理后面访问 azure redis 缓存
- c# - Web api 和 Mvc Razor 中的 Dotnet Core 错误处理
- .net - 如何让我的机器人向给定的电子邮件地址发送电子邮件?
- c# - 如何根据键盘和鼠标活动更改图像?
- java - 是否可以将图像加载库与 odoo 移动框架一起使用
- c# - 使用 CultureInfo.InvariantCulture 时不排除 DateTime
- clojure - Clojure:具有不同数量的递归匿名函数