模板参考变量返回ng-Template内部未定义



已经尝试了此解决方案,但没有任何作用。

我正在使用Angular 7,并尝试获取我放置在 ng-Template 标签中的参考变量。但是它总是返回未定义的

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  
}

我尝试在Angular的所有生命周期挂钩中打印它,但它总是返回不确定的。但是,当我尝试将其放在 ng-template 的外面时,它可以很好地工作。

有什么方法吗?

那是因为尚未呈现ng-template中的内容。

您应该首先使用ngTemplateOutlet

在您的html中添加以下代码,它应该工作

<ng-template #abc>
  <div #xyz>    
  </div>
</ng-template>
<ng-container *ngTemplateOutlet="abc"></ng-container>

demo

它发生的原因是因为ng-template永远不会在 html 上呈现。

按照 Angular docs:

ng-template 是呈现HTML的角元素。它永远不会直接显示。实际上,在呈现视图之前,Angular用评论代替及其内容。

可以转介使用ngTemplateOutlet或使用*ngIf else或类似的东西。它不存在:

更新:

<div *ngIf="someConditionCheck;else abc">
  content here ...
</div>
<ng-template #abc>
  <div #xyz></div>
</ng-template>

您可以在此处找到演示代码。

最新更新