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.
Is there any way in NG2 to create a component based on a string of its class name?
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.
When I load this data as json it looks something like:
user.charts = [
{ type: 'LineChartComponent', position: ... }
{ type: 'BarChartComponent', position: ... }
];
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);
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?
MyComponent
using the string "MyComponent" – Faulkner