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.
Here is my approach:
<ng-container #messageContainer></ng-container>
private createComponent (compClass) {
const compFactory = this.cfr.resolveComponentFactory(compClass);
return this.messageContainer.createComponent(compFactory);;
}
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;
});
}