Angular 2-使用字符串解析组件工厂 [英] Angular 2 - Resolve Component Factory with a string
问题描述
这是针对Angular的2.1.0最终发行版.
This is for the 2.1.0 Final release versions of Angular.
我正在尝试动态实例化从配置JSON文件传递其类型的组件.我能找到的最好的东西是ComponentFactoryResolver
,但是我发现除保存的所有用法似乎都将实际的Type
对象传递给了解析器.
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.
是否可以从字符串中获取Type
?因为目前,将类型作为字符串传递会给我错误:
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
相关代码:
StructureBuilder组件:
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]);
}
}
}
其中config.components是使用Type
作为值的字符串数组.
where config.components is an array of strings that use the Type
as a value.
在模块定义(Structure.module.ts)中
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.
如果我将从configComponents[i]
传入的动态字符串更改为MyComponent
的实际导入类型引用,则它将起作用.
If I change the dynamic string passed in from configComponents[i]
to the actual imported type reference for MyComponent
, it works.
所以基本上,问题是:
是否可以将resolveComponentFactory
与字符串一起使用来解析组件,如果没有,是否可以从字符串值中获取Type
引用?
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
}
然后调用:
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]);
}
}
}
这篇关于Angular 2-使用字符串解析组件工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!