<template>元素未定义@ViewChildren(TemplateRef)

Iev*_*nov 5 angular

如何在组件中获取所有模板(TemplateRef)的集合?它适用于ViewChild,但ViewChildren未定义...

我使用这个问题的解决方案.带有完整示例的Plunker.

  @Component({
    selector: 'my-app',
    template: `
            <div>
              <template #model>...</template>
              <template #color>...</template>
            </div>`
  })
  export class App {
  @ViewChild('model') model;
  @ViewChild('color') color;
  @ViewChildren(TemplateRef) templates: QueryList<TemplateRef>;

  ngAfterContentInit() {
    console.log(this.templates); // undefined
    console.log(this.model); // TemplateRef_ {...}
  }
}
Run Code Online (Sandbox Code Playgroud)

我需要templates一个网格组件,可以为列定义模板.不幸的是,ng-content 不支持动态投影,所以我试图用模板实现它.

Gün*_*uer 8

如果你搬到console.log('child', this.templates);那么ngAfterViewInit()它就可以了。

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

ngAfterContentInit()我原以为它也能发挥作用。看来在这个 Angular 版本ngAfterContentInit()之前运行过ngAfterViewInit()。我之前就确信情况正好相反。

笨蛋的例子