模板引用变量在ng-template内部返回未定义 [英] Template reference variable returns undefined inside ng-template

查看:128
本文介绍了模板引用变量在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆