2017-03-21 29 views
2

我需要一個全局模態打開器服務,可以從任何模塊創建動態組件。 我有多個模塊,每個模塊都有模態組件。我已經簡化我的項目結構是這樣的:動態創建其他模塊的組件

AppModule 
    ---ModalOpenerService 
     --ModalTemplate 
    ---AModule 
      ---ModalComponent1 
      ---ModalComponent2 
      ---SimpleComponent 
    ---BModule 
      ---ModalComponent3 
      ---ModalComponent4 

莫代爾首戰服務有這樣的方法:

@ViewChild('modalContainer', {read: ViewContainerRef}) modalContainer; 

showModal(component: Type<any>,data?:any){ 
    let componentFactory = this.resolver.resolveComponentFactory(component); 
    this.modalContainer.createComponent(componentFactory); 
} 

我希望我的ModalOpenerService能夠創建任何模式組件,並顯示它。但是問題在於模態組件屬於不同的模塊,模態開罐器在其噴油器的組件工廠列表中找不到它們。

No component factory found for ModalComponent1. Did you add it to @NgModule.entryComponents 

顯然,ModalComponent1不是AppModule的成員。

我可以通過使工廠方法作爲參數,而不是組件類型像這樣打開模態

//In SimpleComponent, I call my ModalOpenerService to open modal1. Because 
//the simpleComponent's parent injector (AModule's injector) can find Modal1, 
//this.resolver can resolve Modal1. 
showModal1(){ 
    this.modalOpenerService.showModal(this.resolver.resolveComponentFactory(ModalComponent1)); 
} 

在ModalOpenerService

@ViewChild('modalContainer', {read: ViewContainerRef}) modalContainer; 

showModal(factory:ComponentFactory<any>, data?:any){ 
    this.modalContainer.createComponent(factory); 
} 

因此,模塊創建自己的組件和它們能夠在entryComponents陣列中找到該組件。

我們仍然有一個問題,因爲在AppModule的範圍內創建的任何模態組件,並且如果我想顯示來自模態的另一個模態,AppModule的噴油器仍然無法找到它。

一個解決方案可以是將所有模態放入同一個模塊中,但是我希望所有模態都在它自己的模塊中。

任何結構的設計建議,也歡迎

回答

0

你需要有ModalOpenerService作爲單獨的模塊是

export class ModelModule { 
    static WithComponents(components: Array<Type<any>>): Array<any> { 
     return { 
      ngModule: ModelModule, 
      providers: [ 
       { provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true } 
      ] 
     } 
    } 
} 

而且從AModule和BModule可以包括ModelModule如下

@NgModule({ 
    imports: [BrowserModule, ModelModule.WithComponents([ModalComponent1, ModalComponent2])], 
    declarations: [AppComponent, ModalComponent1, ModalComponent2], 
    bootstrap: [AppComponent], 
    providers: [] 
}) 
export class AModule { } 
+1

你答案很有趣,但我不明白什麼是AnchorModule?你是否試圖在導入ModalModule時將模態組件綁定到ModalModule? – omeralper

+0

我修改了代碼。不需要AnchorModule –