我想知道是否可以使用模板引用变量访问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);
}
<ng-template>
是一个用于呈现HTML的Angular元素。它永远不会直接显示。实际上,在渲染视图之前,Angular用注释替换<ng-template>
及其内容。
只要您在某处使用模板,例如:
<ng-content *ngTemplateOutlet="first"></ng-content>
您还可以通过Viewchild访问它的内容。