我一直在研究Angular 2 API ComponentResolver以及DynamicComponentResolver创建动态组件,但我有一些不同于那些API提供的东西.
在NG2中是否有任何方法可以基于其类名字符串创建组件?
例如,我正在构建一个可配置的图表仪表板.每个用户的布局都存储在数据库中,说明他们需要2x折线图,3x条形图等.
当我将这些数据加载为json时,它看起来像:
user.charts = [
{ type: 'LineChartComponent', position: ... }
{ type: 'BarChartComponent', position: ... }
];
Run Code Online (Sandbox Code Playgroud)
type我想要反射创建的组件的类名在哪里.
到目前为止,我有以下内容:
this.chartMap = {
'LineChartComponent': LineChartComponent
};
let config = this.configuration;
let chartComponentType = this.chartMap[config.type];
let factory = this.componentFactory.resolveComponentFactory(chartComponentType);
let component = factory.create(this.injector);
component.instance.configuration = config;
this.chartContainer.insert(component.hostView);
Run Code Online (Sandbox Code Playgroud)
但整个想法是消除对的需要chartMap.如何在不引用类型的情况下基于字符串反射性地创建此类?
是否有可能Type<T>从string值获取component()的类型?Smth喜欢:
let typeStr: string = 'MyComponent';
let type: any = resolveType(typeStr); // actual type
Run Code Online (Sandbox Code Playgroud) 这是针对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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
其中config.components是一个使用Typeas作为值的字符串数组.
并在模块定义(Structure.module.ts)
@NgModule({
declarations: [
MyComponent,
StructureBuilder_Cmp
],
entryComponents: [
MyComponent
]
//Etc...
});
Run Code Online (Sandbox Code Playgroud)
就稀疏文档而言,这正是你应该如何做到的.
如果我将传入的动态字符串更改为configComponents[i]实际导入的类型引用MyComponent,则可以.
基本上,问题是:有没有办法使用resolveComponentFactory字符串来解析组件,如果没有,是否有办法Type从字符串值获取引用?