Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional importing/overriding module imports

Tags:

angular

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!

like image 715
Vlad Vidac Avatar asked Nov 13 '19 10:11

Vlad Vidac


1 Answers

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.

like image 190
Eldar Avatar answered Nov 19 '22 05:11

Eldar