2017-06-16 97 views
1

是否有辦法向動態添加組件到聲明和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服務它工作正常。

+0

爲什麼不直接寫'entryComponents:[AppInfo.components],'? – echonax

+0

我不認爲你可以將一個* const *變量傳遞給@NgModule。生產版本不運行模塊文件,而是掃描它以提取元數據以提前編譯。因此它不知道在上面的代碼中要做什麼。我認爲它在文件中解釋了這一點。 – cgTag

+0

@echonax 我的AppInfo.components不僅僅是一個組件數組。它的類型是{name:string,component:Component} []。我讓這個例子更容易理解。 – geronimo678

回答

2

我做的是出口組件陣列和使用,在@NgModule

可以內部組件和開發組件之間的分裂這一點。

Internal.components.ts

export const INTERNAL_COMPONENTS = [ 
     FooterComponent, 
     HeaderComponent, 
     SideBarComponent 
]; 

Developer.components.ts

export const DEVELOPER_COMPONENTS = [ 
     WidgetComponent, 
     CustomerComponent, 
     NewFeatureComponent 
]; 

然後你將它們導入到你的模塊文件,並使用它們。

import {INTERNAL_COMPONENTS} from './Internal.components.ts'; 
import {DEVELOPER_COMPONENTS} from './Developer.components.ts'; 

@NgModule({ 
    declarations: [ 
     INTERNAL_COMPONENTS, 
     DEVELOPER_COMPONENTS 
    ], 
    exports: [ 
     INTERNAL_COMPONENTS, 
     DEVELOPER_COMPONENTS 
    ] 
}) 
export class AppModule { 

} 

將條目組件留作單個主要組件。

+0

謝謝!訪問導出的常量工作正常。 – geronimo678