【发布时间】:2016-10-26 02:32:15
【问题描述】:
这是 Angular 的 2.1.0 最终版本。
我正在尝试动态实例化一个类型是从配置 JSON 文件传递的组件。我能找到的最好的东西是ComponentFactoryResolver,但是我发现的所有用法除了一个似乎都是将实际的Type 对象传递给解析器。
有没有办法从字符串中获取Type?因为目前,将类型作为字符串传递会给我错误:
No component factory found for MyComponent
相关代码:
StructureBuilder 组件:
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 作为值的字符串数组。
并且在模块定义中(Structure.module.ts)
@NgModule({
declarations: [
MyComponent,
StructureBuilder_Cmp
],
entryComponents: [
MyComponent
]
//Etc...
});
就稀疏文档而言,这正是您应该这样做的方式。
如果我将传入的动态字符串从configComponents[i] 更改为MyComponent 的实际导入类型引用,它会起作用。
所以基本上,问题是:
有没有办法将resolveComponentFactory 与字符串一起使用来解析组件,如果没有,有没有办法从字符串值中获取Type 引用?
【问题讨论】:
-
你想将
'MyComponent'作为字符串传递给resolveComponentFactory吗? -
是的,对不起,我就是这个意思。
-
@yurzui 该答案的问题在于它使用了解析器的私有内部属性。诸如此类的私有内容在未来的版本中可能会发生变化,因此这确实不是一个可靠的解决方案。
-
是的,你是对的。这样你就必须声明
map = { "MyComponent": MyComponent }之类的东西并使用它
标签: angular typescript2.0