2

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.

Narm
  • 10,677
  • 5
  • 41
  • 54
Sumit Sharma
  • 23
  • 2
  • 5
  • So you want the value of the `message` property to update in the dynamic component every time it changes **or** do you want multiple dynamic components generated with different "messages"? – Narm Sep 11 '19 at 15:08
  • i want multiple dynamic components generated with different "messages " and we can update the values of messages on any click event – Sumit Sharma Sep 13 '19 at 11:46

1 Answers1

1

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.

Andrei Gătej
  • 11,116
  • 1
  • 14
  • 31
  • I tried to use `comp.changeDetectorRef.detectChanges();` but it stops the loop and so other components dont get created – Jaydeep Feb 04 '20 at 02:22