【发布时间】:2023-03-03 09:46:01
【问题描述】:
我在渲染组件时遇到问题 这是代码示例。
<my-component>
<ng-template *ngFor="let item of data">
<child-component>
<div>
{{ data.title }}
</div>
</child-component>
</ng-template>
</my-component>
在 my-component.ts 中
@ContentChildren(TemplateRef) template: QueryList<TemplateRef<any>>;
ngAfterContentInit(): void {
this.template.forEach(item => {
const template = this.viewTemplateRef.createEmbeddedView(item);
template.detectChanges();
});
}
当我将某些内容推送到数据中时,我需要显示一个新的子组件。如果我尝试做这样的事情:
this.template.changes.subscribe((result) => {
this.template.forEach(item => {
this.viewTemplateRef.createEmbeddedView(item);
});
});
我有无限循环。这样做的正确方法是什么?
【问题讨论】:
-
你能在 stackblitz.com 上提供一个演示代码吗?这个问题需要进一步澄清
-
如果你想告诉子组件它们应该被刷新,你可以在将新项目推送到数据数组后添加
this.changeDetectorRef.detecChanges()。是否需要 ng-template? -
@ShashankVivek stackblitz.com/edit/…
-
@KamilAugustyniak 请看我的例子stackblitz.com/edit/angular-8pvrhq
-
为什么要在那里使用
ViewContainerRef?
标签: angular typescript rxjs angular8