【问题标题】:Dynamically create components of other modules动态创建其他模块的组件
【发布时间】:2017-08-13 05:26:32
【问题描述】:

我需要一个可以从任何模块创建动态组件的全局模式打开器服务。 我有多个模块,每个模块都有模态组件。我已经像这样简化了我的项目结构:

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

Modal opener 服务有一个这样的方法:

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

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

我希望我的 ModalOpenerService 能够创建任何模态组件并显示它。但问题是 modal 组件属于不同的模块,modal opener 无法在其注入器的组件工厂列表中找到它们。

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 的注入器仍然无法找到它。

一种解决方案是将所有模态与ModalOpenerService 放在同一个模块中,但我希望所有模态都在其自己的模块中。

也欢迎任何结构设计建议

【问题讨论】:

  • 遇到同样的问题。已经找到了一个很好的方法?
  • @PieterDegraeuwe 不幸的是没有。我们试图在来自不同模块的弹出窗口上打开一些弹出窗口,但是角度不适用于动态组件。

标签: javascript angular typescript angular2-services


【解决方案1】:

您需要将 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 { }

【讨论】:

  • 你的回答很有趣,但我不明白什么是 AnchorModule?您是否尝试在导入 ModalModule 时将模态组件绑定到 ModalModule?
猜你喜欢
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 2021-09-14
  • 2023-04-09
  • 2012-08-21
相关资源
最近更新 更多