模板引用变量在ng-template内部返回未定义 [英] Template reference variable returns undefined inside ng-template
问题描述
已经尝试过此和
Already tried this and this solution but nothing worked.
我正在使用Angular 7,并尝试获取放置在 ng-template 标签内的参考变量.但是它总是返回 undefined
I am using Angular 7 and trying to get a reference variable which I've placed inside the ng-template tag. But it always returns undefined
test-component.html
<ng-template #abc>
<div #xyz>
</div>
</ng-template>
test-component.ts
@ViewChild('abc') abc: ElementRef; //---> works fine
@ViewChild('xyz') xyz: ElementRef; //---> undefined
test-component.ts
ngAfterViewInit(){
console.log(this.xyz); //---> undefined
}
我已经尝试过在角度的所有生命周期挂钩中打印它,但是它总是返回未定义的.但是,当我尝试将其放在 ng-template 之外时,它就可以正常工作.
I've tried printing it in all the life cycle hooks of angular but it always returns undefined. But when I try putting it in out side of ng-template it works perfectly.
有什么办法吗?
推荐答案
这是因为 ng-template
中的内容尚未呈现.
That is because, the content inside ng-template
is not yet rendered.
您应该首先使用 ngTemplateOutlet
激活它.
You should first activate it using ngTemplateOutlet
.
在您的html中添加以下代码,它应该可以工作
Add the following code in your html, it should work
<ng-template #abc>
<div #xyz>
</div>
</ng-template>
<ng-container *ngTemplateOutlet="abc"></ng-container>
这篇关于模板引用变量在ng-template内部返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!