【发布时间】:2017-03-24 12:57:07
【问题描述】:
我一直在研究用于创建动态组件的 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 的需求。如何在不引用类型的情况下基于字符串反射性地创建此类?
【问题讨论】:
标签: angular angular2-components angular2-injection