如何使用模板引用变量访问ng-template中的模板内容

问题描述 投票:0回答:1

我想知道是否可以使用模板引用变量访问ng-template中的模板组件?我已经尝试过使用@ViewChild和@ContentChild,但它们似乎都没有工作示例:我想访问app-common的内容

<ng-template #first>
<app-common #second><app-common>
</ng-template>

@ViewChild('second') second1: ElementRef;
@ContentChild('second') second2: ElementRef;

ngAfterViewInit() {
  console.log(this.second1);
}

ngAfterContentInit() {
  console.log(this.second2);
}
angular angular2-template viewchild ng-template
1个回答
0
投票

<ng-template>是一个用于呈现HTML的Angular元素。它永远不会直接显示。实际上,在渲染视图之前,Angular用注释替换<ng-template>及其内容。

Source

只要您在某处使用模板,例如:

<ng-content *ngTemplateOutlet="first"></ng-content>

您还可以通过Viewchild访问它的内容。

© www.soinside.com 2019 - 2024. All rights reserved.