如何在组件中获取所有模板(TemplateRef)的集合?它适用于ViewChild,但ViewChildren未定义...
我使用了这个question的解决方案 . 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_ {...}
}
}
我需要 templates
作为网格组件,可以为列定义模板 . 不幸的是ng-content doesn't support动态投影,所以我试图用模板实现它 .
1 回答
如果您将
console.log('child', this.templates);
移动到ngAfterViewInit()
那么它可以工作 .我曾预计它也会在
ngAfterContentInit()
中运作 . 似乎在这个Angular版本ngAfterContentInit()
在ngAfterViewInit()
之前运行 . 我确信这是早先的另一种方式 .Plunker example