Vlad Vidac
Vlad Vidac

Reputation: 998

Conditional importing/overriding module imports

I want to propagate a module config from one module to another. I find this difficult to explain in more detail so I'll try with an example.

I have a module that goes something like:

@NgModule({
  declarations: [
    ButtonComponent,
    TranslatePipe,
  ],
  imports: [
    CommonModule,
  ],
  exports: [
    ButtonComponent,
  ],
})
export class ButtonModule {
  static withConfig(config: ButtonModuleConfig): ModuleWithProviders {
    return {
      ngModule: ButtonModule,
      providers: [
        {
          provide: TranslateService,
          useClass: config.translateService,
        },
      ],
    };
  }
}

And I want to do something like this is another module:

@NgModule({
  declarations: [
    PageComponent,
  ],
  imports: [
    CommonModule,
    ButtonModule, // the one defined above without overriding the TranslateService
  ],
  exports: [
    PageComponent,
  ],
})
export class PageModule {
  static withConfig(config: PageModuleConfig): ??? {
    return {
      ngModule: PageModule,
      imports: [
        ButtonModule.withConfig({
           translateService: config.translateService,
      ],
    };
  }
}

Is there a thing like ModuleWithProviders but more like ModuleWithImports?

Thanks!

Upvotes: 5

Views: 473

Answers (1)

Eldar
Eldar

Reputation: 10790

If you make your page module to provide value for translate service it will work.

export class PageModule {
  static withConfig(config: any): ModuleWithProviders {
    return {
      ngModule: PageModule,
      providers: [
        {
          provide: TranslateService,
          useValue: config.translateService
        }
      ]
    };
  }
}

Here is the sample stackblitz application.

Upvotes: 4

Related Questions