mercredi 27 novembre 2019

Angular 7 - Dynamic Loading Component with Reflection

I need to load component dynamically in a specific place knowing only the name of component. I read about DynamicLoading on Official Site but its a simple case when you have only one component at time and you have a prepared list of component.

I need something linke this:

CONTAINER COMPONENT

<div>
   [HOOK-PLACE]
</div>

var clist = [ "HelloComponent" , "FarewellComponent"];

I need to iterate clist and add dynamically, inside HOOK-PLACE, all component in list having their name.

RESULT:

<div>
   <HelloComponent />
   <FarewellComponent />
</div>

I see an example here on Stackoverflow, where a guy used:

@ViewChild('container', { static: true, read: ViewContainerRef }) entry: ViewContainerRef;

as entry point, and then:

this.entry.clear();
const factory = this.resolver.resolveComponentFactory(HelloComponent);
const componentRef = this.entry.createComponent(factory);
componentRef.instance.name = this.name;

The problem with this solution is: 1. Only one component is loaded; 2. HelloComponent is set directly. Its not a "string";

If you ask why I need this its because I have a list of component on DB as String and I have to load the component as a consequence of a DB call. I have all the component compiled but is the DB to decide which ones to use.

Thanks.





Aucun commentaire:

Enregistrer un commentaire