已经尝试过this https://stackoverflow.com/questions/45677905/angular4-component-reference-inside-ng-template and this https://stackoverflow.com/questions/49127590/angular-5-get-reference-inside-ng-template解决方案但没有任何效果。
我正在使用 Angular 7 并尝试获取一个引用变量,该变量已放置在ng-模板标签。但它总会回归不明确的
测试组件.html
<ng-template #abc>
<div #xyz>
</div>
</ng-template>
测试组件.ts
@ViewChild('abc') abc: ElementRef; //---> works fine
@ViewChild('xyz') xyz: ElementRef; //---> undefined
测试组件.ts
ngAfterViewInit(){
console.log(this.xyz); //---> undefined
}
我尝试在 Angular 的所有生命周期钩子中打印它,但它总是返回未定义。但是当我尝试把它放在外面时ng-模板它工作得很好。
有什么办法吗?
那是因为,里面的内容ng-template
尚未渲染。
您应该首先使用激活它ngTemplateOutlet
.
在你的html中添加以下代码,它应该可以工作
<ng-template #abc>
<div #xyz>
</div>
</ng-template>
<ng-container *ngTemplateOutlet="abc"></ng-container>
DEMO https://stackblitz.com/edit/angular-1pvpdy?file=src%2Fapp%2Fapp.component.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)