我在渲染组件时遇到问题这是代码示例。
<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);
});
});
我有无限循环。什么是正确的方法?
<my-component>
<child-component *ngFor="let item of data">
<div>
{{ data.title }}
</div>
</child-component>
</my-component>
为我解决。