0

我想知道是否可以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);
}
4

1 回答 1

0

The <ng-template> is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the <ng-template> and its contents with a comment.

Source

As soon as you use the template somewhere like e.g.:

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

you will also be able to access it's content via a Viewchild.

于 2018-09-04T16:19:26.830 回答