1
votes

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. 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

 @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:

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

Using *ngFor the dynamic components are not rendered in the DOM. I have tried also to create ng-template placeholder host hardcoded inside the 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?

2

2 Answers

1
votes

Have you tried using ngComponentOutlet

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

Finally, the provblem solved by using trackBy inside *ngFor loop

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;
}