Search code examples
angulartypescriptangular-dynamic-components

Load dynamic component multiple times with different data


I need to load a dynamic component multiple times and pass data dynamically based on some value so that it will load with runTime data.

I have tried below example https://dzone.com/articles/how-to-dynamically-create-a-component-in-angular

as per example we have one messageComponent that have "message" property and in hostComponent we are adding one template in html file like

<div style="text-align:center">
     <h1>
         Welcome to {{ title }}!
     </h1>
     <template #messagecontainer>
     </template>
 </div>

so here in the place of template tag our messageComponent will replace.

I need something like we can iterate this template multiple times and pass different value of "message" dynamically in messageComponent.


Solution

  • Here is my approach:

    • in your template, create a container for all the messages
    <ng-container #messageContainer></ng-container>
    
    • add a function that will allow us to create a component and insert it into the view
    private createComponent (compClass) {
       const compFactory = this.cfr.resolveComponentFactory(compClass);
    
       return this.messageContainer.createComponent(compFactory);;
     }
    
    • load the component multiple times, depending on the incoming data; we will also keep track of the components which have been loaded in order to be able to destroy them when we need to load another dynamic component.
     private loadNewComponentList () {
       this.messages.forEach((msg, idx) => {
         this.destroyCompFromList(this.componentList[idx]);
    
         const comp = this.createComponent(componentMap[this._crtComp]);
    
         (comp.instance as any).message = msg;
    
         comp.changeDetectorRef.detectChanges();
    
         this.componentList[idx] = comp;
       });
     }
    

    Here is a StackBlitz demo.