简体   繁体   English

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

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

I would like to insert a dynamic list of components inside parent component template using ngFor directive to create ng-template host placeholders for each component in the list.我想使用 ngFor 指令在父组件模板中插入一个动态组件列表,为列表中的每个组件创建 ng-template 主机占位符。 What I have tried:我尝试过的:

component template where dynamic components will be inserted:将插入动态组件的组件模板:

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

component.ts组件.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' input is an array of objects containing the dynamic component instances in the following form: 'components' 输入是包含以下形式的动态组件实例的对象数组:

[ 
   { 'component' : DynamicComponent1 },
   { 'component' : DynamicComponent2 }
]

Using *ngFor the dynamic components are not rendered in the DOM.使用 *ngFor 动态组件不会在 DOM 中呈现。 I have tried also to create ng-template placeholder host hardcoded inside the template:我还尝试在模板内创建硬编码的 ng-template 占位符主机:

component template:组件模板:

<div >
   <ng-template #kalasehost></ng-template>
 </div>
 <div >
   <ng-template #kalasehost></ng-template>
 </div>

Using this template markup dynamic templates are rendered as expected.使用此模板标记动态模板按预期呈现。 Could anyone tell me what I am doing wrong using ngFor directive?谁能告诉我我在使用 ngFor 指令时做错了什么?

您是否尝试过使用ngComponentOutlet

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

Finally, the provblem solved by using trackBy inside *ngFor loop最后,通过在 *ngFor 循环中使用 trackBy 解决了问题

component.html:组件.html:

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

component.ts:组件.ts:

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

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

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