【问题标题】:Create multiple different dynamic components using ngFor directive Angular使用 ngFor 指令 Angular 创建多个不同的动态组件
【发布时间】: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


    【解决方案1】:

    您是否尝试过使用ngComponentOutlet

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

    【讨论】:

    • 我已经尝试过了,但在这种情况下并没有真正的帮助......通过在 ngFor 循环中使用 trackBy 解决了这个问题......
    【解决方案2】:

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

    component.html:

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

    component.ts:

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

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 2018-11-09
      相关资源
      最近更新 更多