【发布时间】:2017-03-01 10:54:13
【问题描述】:
我想用 NgTemplateOutlet 创建孩子。
我有这个example plunkr,我有子组件和父组件,父组件有一个使用 ngTemplateOutlet 呈现的输入模板:
@Component({
selector: 'parent',
template: `
<div>parent</div>
<ng-container *ngTemplateOutlet="template1"></ng-container>
<div *ngFor="let child of children; let i = index">{{i}}</div>
{{children.length}}
`
})
export class Parent {
@Input() template1;
children = [];
@ViewChildren(Child) viewList: QueryList<Child>;
updateElements() {
setTimeout(() => this.children = this.viewList.toArray());
}
ngAfterViewInit() {
this.viewList.changes.subscribe(() => this.updateElements());
this.updateElements();
}
}
父组件尝试使用ViewChildren 获取Child 子组件,但不起作用。
有人知道怎么弄吗?
另一方面,我写了other plunkr,我在其中使用 ngFor 来渲染几个子组件并且它可以工作。
由于 ngFor 和 ngTemplateOutlet 都使用viewContainerRef.createEmbeddedView,我认为两种方法应该以相同的方式工作。
为什么不呢?
PS:我使用的是 Angular 4.0.0-rc1,但我认为 Angular 2.x 也是如此
【问题讨论】:
标签: angular