This is for the 2.1.0 Final release versions of Angular.
I'm trying to dynamically instantiate a component who's type is passed from a config JSON file. The best thing I can find is ComponentFactoryResolver, however all usages that I have found save one seem to be passing actual Type objects to the resolver.
Is there a way to get the Type from a string? Because presently, passing the type as a string gives me the error:
No component factory found for MyComponent
Relevant code:
StructureBuilder component:
private renderComponent(config:any) {
let configComponents = config.components;
if(config.hasOwnProperty('components') && configComponents.length){
for(let i = 0, len = configComponents.length; i < len; i++){
this.componentResolver.resolveComponentFactory(configComponents[i]);
}
}
}
where config.components is an array of strings that use the Type as a value.
And in the module definition (Structure.module.ts)
@NgModule({
declarations: [
MyComponent,
StructureBuilder_Cmp
],
entryComponents: [
MyComponent
]
//Etc...
});
As far as can tell with the sparse docs, this is exactly how you're supposed to do it.
If I change the dynamic string passed in from configComponents[i] to the actual imported type reference for MyComponent, it works.
So basically, the question is:
Is there a way to use resolveComponentFactory with strings to resolve a component, and if not, is there way to get a Type reference from a string value?
My solution for now is to do what I really wanted to avoid, which is maintaining a key/val registry.
let componentRegistry = {
'SomeComp1': SomeComp1,
'SomeComp2': SomeComp2
}
And then call it with:
private renderComponent(config:any) {
let configComponents = config.components;
if(config.hasOwnProperty('components') && configComponents.length){
for(let i = 0, len = configComponents.length; i < len; i++){
let comp = configComponents[i];
this.componentResolver.resolveComponentFactory(this.componentRegistry[comp]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With