我一直在尋找用於創建動態組件的ComponentResolver
和DynamicComponentResolver
的Angular 2 API,但我有些東西與這些API提供的不同。ng2 - 基於模板動態創建組件
有沒有什麼辦法在NG2創建一個基於它的類名字符串的組件?
例如,我建立一個可配置的圖表儀表板。每個用戶的佈局存儲在數據庫中,說明他們想在這裏2個折線圖,3柱狀圖在那裏,等
當我加載這個數據爲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公開公開,我寧願使用類名稱而不是選擇器。這個問題變得更像是一個Typescript問題而不是一個Angular問題。也就是說,如何在使用字符串「MyComponent」 – parliament
這個快速更新之前實例化MyComponent類型,然後我甚至評論了lol。你可以請更新新版本的plnkr,我認爲這兩個鏈接是相同的。你可能需要叉它 – parliament
我已經添加了代碼 – yurzui