繁体   English   中英

使用 ngFor 指令 Angular 创建多个不同的动态组件

[英]Create multiple different dynamic components using ngFor directive Angular

我想使用 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 指令时做错了什么?

您是否尝试过使用ngComponentOutlet

<div *ngFor="let component of components" [ngComponentOutlet]="component.component"></div>

最后,通过在 *ngFor 循环中使用 trackBy 解决了问题

组件.html:

<div *ngFor="let component of components;trackBy:identify;let i = index">
 <ng-template #dynamiccomponenthost></ng-template>
</div>

组件.ts:

identify(index, item) {
    return item && item.id;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM