ng2-基于模板动态创建组件 [英] ng2 - dynamically creating a component based on a template
问题描述
我一直在寻找用于创建动态组件的ComponentResolver
和DynamicComponentResolver
的Angular 2 API,但是与这些API提供的功能有所不同.
I've been looking at the Angular 2 APIs for ComponentResolver
and DynamicComponentResolver
for creating dynamic components, but I have something different in mind than those APIs offer.
NG2中是否有任何方法可以根据其类名的字符串创建组件?
Is there any way in NG2 to create a component based on a string of its class name?
例如,我正在构建一个可配置的图表仪表板.每个用户的布局都存储在数据库中,说明他们要在这里使用2个折线图,在这里需要3个条形图,等等.
For example, Im building a configurable charts dashboard. Each user's layout is stored in the database, stating they want 2x line charts here, 3x bar charts there, etc.
当我将此数据加载为json时,它看起来像:
When I load this data as json it looks something like:
user.charts = [
{ type: 'LineChartComponent', position: ... }
{ type: 'BarChartComponent', position: ... }
];
type
是要反射创建的组件的类名.
Where type
is the component's class name that I want to reflectively create.
到目前为止,我有以下内容:
So far I have the following:
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
的需要.如何在不引用类型的情况下基于字符串反射性地创建此类?
But the whole idea is to eliminate the need for chartMap
. How can I reflectively create this class based on a string without having a reference to the type?
推荐答案
Update2:
正如@estus在带有className的注释版本中提到的那样,不能与缩小一起使用.为此,您可以
As @estus mentioned in comments version with className won't work with minification. To do it working with minification you can
1)在每个entryComponents
上添加一些静态键,例如:
1) add some static key on each of your entryComponents
like:
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);
更新1:
此处是组件类名称的版本
Here's version from component`s class name
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);
- 如何使用angular2?
- How to load component dynamically using component name in angular2?
旧版本
您可以通过组件选择器获得工厂,但必须使用私有属性.
You can get factory by component selector but you have to use private property.
可能看起来像这样:
const factories = Array.from(this.resolver['_factories'].values());
const factory = factories.find((x: any) => x.selector === selector);
Plunker Example
这篇关于ng2-基于模板动态创建组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!