是否有辦法向動態添加組件到聲明和entryComponents屬性(Angular 4,angular/cli 1.1.2)?如何在Angular 4和@ angular/cli中動態添加組件到NgModule?
背景:我創建了一個AppInfo.ts,開發人員可以在其中定義將使用ComponentFactoryResolver動態加載的附加組件(類似小部件)。 此AppInfo.ts由組件的一個靜態數組(AppInfo.components)組成。
如何將此數組的元素推送到NgModule裝飾器?
我用NG成爲了這個解決方案的工作,但沒有使用NG構建--prod:
export const ngmodule = {
declarations: [...],
entryComponents:[ ],
imports: [...],
bootstrap: [
AppComponent
],
providers: [...]
};
for (let i = 0; i < AppInfo.components.length; i++) {
const comp = <any> AppInfo.components[i];
ngmodule.entryComponents.push(comp);
ngmodule.declarations.push(comp);
}
@NgModule(ngmodule)
如果我嘗試使用NG構建--prod我得到這個錯誤打造我的應用程序:
ERROR in Cannot determine the module for class DynCompExample in /Users/x/Documents/x/src/app/x/x/DynCompExample.component.ts! Add DynCompExample to the NgModule to fix it.
但是,如果我使用ng服務它工作正常。
爲什麼不直接寫'entryComponents:[AppInfo.components],'? – echonax
我不認爲你可以將一個* const *變量傳遞給@NgModule。生產版本不運行模塊文件,而是掃描它以提取元數據以提前編譯。因此它不知道在上面的代碼中要做什麼。我認爲它在文件中解釋了這一點。 – cgTag
@echonax 我的AppInfo.components不僅僅是一個組件數組。它的類型是{name:string,component:Component} []。我讓這個例子更容易理解。 – geronimo678