用于ng-template的ViewChildren

sso*_*nez 8 angular

我有一个angular2组件,模板看起来像这样:

<div>
    <div><ng-template #left></ng-template></div>
    <div><ng-template #right></ng-template></div>
</div>
Run Code Online (Sandbox Code Playgroud)

我希望能够检索所有ng-template元素的引用,ViewChildren但我不知道我需要在括号之间传递的类型.

Gün*_*uer 12

@ViewChildren(TemplateRef) templates: QueryList<TemplateRef>;

ngAfterViewInit() {
  console.log(this.templates.toArray());
}
Run Code Online (Sandbox Code Playgroud)

要么

@ViewChild('left') left:TemplateRef;
@ViewChild('right') right:TemplateRef;

ngAfterViewInit() {
  console.log(this.left, this.right);
}
Run Code Online (Sandbox Code Playgroud)

  • 嘿,我刚刚使用`ViewContainerRef`写了[关于DOM操作的文章](https://medium.com/@maximus.koretskyi/exploring-angular-dom-abstractions-80b3ebcfc02#.lc9ev4gg0!),如果你有时间。 (2认同)
  • 关于缺少泛型的视觉工作室代码投诉:`[ts]泛型类型'TemplateRef <C>'需要1种类型的参数`我不知道,不应该是`ElementRef`? (2认同)
  • 泛型类型适用于模板上下文对象。如果您不使用上下文对象,则只需使用“any”。 (2认同)