My goal:
- I want to find a way to use something similar to the "resolveComponentFactory()", but with a 'string' identifier to obtain Component Factories.
- Once I have them, I plan to utilize the "createComponent(Factory)" method.
Check out this Plnkr Example -> here
In the example code, you will come across the AddItem
method
addItem(componentName:string):void{
let compFactory: ComponentFactory;
switch(componentName){
case "image":
compFactory = this.compFactoryResolver.resolveComponentFactory(PictureBoxWidget);
break;
case "text":
compFactory = this.compFactoryResolver.resolveComponentFactory(TextBoxWidget);
break;
}
//I am looking for a way to dynamically resolve a component based on a string
//without having to hard code all possible options
this.container.createComponent(compFactory);
}
The "compFactoryResolver:ComponentFactoryResolver" is injected in the constructor.
While using a switch statement works, it's not the most efficient solution and can lead to maintenance issues.
Inspecting the ComponentFactoryResolver in the console, I noticed that it contains a Map with different factories.
CodegenComponentFactoryResolver {_parent: AppModuleInjector, _factories: Map}
However, accessing this map directly seems challenging as it is private.
Is there a better approach than creating my own class to access this factory list?
I've seen many discussions on dynamic component creation, but here I am specifically trying to retrieve factories using strings as keys.
Any suggestions or guidance would be greatly appreciated.
Thank you for your help.