【发布时间】:2021-01-13 01:33:00
【问题描述】:
我想使用 ngFor 指令在父组件模板中插入一个动态的组件列表,以便为列表中的每个组件创建 ng-template 主机占位符。我尝试过的:
将插入动态组件的组件模板:
<div *ngFor="let component of components;let i = index">
<ng-template #dynamiccomponenthost></ng-template>
</div>
组件.ts
@Input()
components: any;
@ViewChildren('dynamiccomponenthost', { read: ViewContainerRef }) cHost: QueryList<ViewContainerRef>;
ngAfterViewInit() {
this.loadComponents();
}
private loadComponents(): void {
this.cHost.map((vcr: ViewContainerRef, index: number) => {
const factory = this.componentFactoryResolver.resolveComponentFactory(this.components[index].component);
vcr.clear();
vcr.createComponent(factory);
});
'components' 输入是一个包含动态组件实例的对象数组,格式如下:
[
{ 'component' : DynamicComponent1 },
{ 'component' : DynamicComponent2 }
]
使用 *ngFor 动态组件不会在 DOM 中呈现。我还尝试在模板内创建硬编码的 ng-template 占位符主机:
组件模板:
<div >
<ng-template #kalasehost></ng-template>
</div>
<div >
<ng-template #kalasehost></ng-template>
</div>
使用此模板标记动态模板按预期呈现。谁能告诉我使用 ngFor 指令我做错了什么?
【问题讨论】:
标签: angular