代码之家  ›  专栏  ›  技术社区  ›  Arthur Decker

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

  •  0
  • Arthur Decker  · 技术社区  · 6 年前

    我想知道是否可以访问 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);
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   sevic    6 年前

    这个 <ng-template> 是呈现HTML的角度元素。它是 从不直接显示。事实上,在渲染视图之前,角度 替换 <NG模板 内容和评论。

    Source

    一旦使用模板,例如:

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

    您还可以通过一个viewchild访问它的内容。