我一直在寻找ComponentResolver
和DynamicComponentResolver
的Angular 2 API来创建动态组件,但我想到的不同于那些API。
NG2中是否有任何方法可以根据其类名字符串创建组件?
例如,我正在建立一个可配置的图表仪表板。每个用户的布局都存储在数据库中,说明他们需要2x折线图,3x条形图等等。
当我将这些数据加载为json时,它看起来像:
user.charts = [
{ type: 'LineChartComponent', position: ... }
{ type: 'BarChartComponent', position: ... }
];
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);
但是整个想法是消除对chartMap
的需求。如何在不引用类型的情况下基于字符串反射性地创建此类?
答案 0 :(得分:17)
<强> UPDATE2:强>
正如@estus在评论版中提到的那样,带有className的版本不能用于缩小。要做到缩小,你可以
1)在每个entryComponents
上添加一些静态密钥,如:
export LineChartComponent {
static key = "LineChartComponent";
}
然后将此key
用作唯一。
const factoryClass = <Type<any>>factories.find((x: any) => x.key === compClassKey);
2)创建像
这样的字典export const entryComponentsMap = {
'comp1': Component1,
'comp2': Component2,
'comp3': Component3
};
然后
const factory = this.resolver.resolveComponentFactory(entryComponentsMap.comp1);
<强> UPDATE1:强>
这是组件类名
的版本const factories = Array.from(this.resolver['_factories'].keys());
const factoryClass = <Type<any>>factories.find((x: any) => x.name === compClassName);
const factory = this.resolver.resolveComponentFactory(factoryClass);
旧版
您可以按组件选择器获取工厂,但必须使用私有属性。
它可能看起来像:
const factories = Array.from(this.resolver['_factories'].values());
const factory = factories.find((x: any) => x.selector === selector);
<强> Plunker Example 强>
答案 1 :(得分:1)
也可以通过导入:
进行迭代import * as possibleComponents from './someComponentLocation'
...
let inputComponent;
for(var key in possibleComponents ){
if(key == componentStringName){
inputComponent = possibleComponents[key];
break;
}
}
更新:或只是: - )
let inputComponent = possibleComponents[componentStringName]
然后您可以创建组件实例,例如:
if (inputComponent) {
let inputs = {model: model};
let inputProviders = Object.keys(inputs).map((inputName) => { return { provide: inputName, useValue: inputs[inputName] }; });
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
let injector: ReflectiveInjector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.dynamicInsert.parentInjector);
let factory = this.resolver.resolveComponentFactory(inputComponent as any);
let component = factory.create(injector);
this.dynamicInsert.insert(component.hostView);
}
请注意,组件必须位于@NgModule entryComponents
中