Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Angular providers provided in root

I import a modal library of ng-bootstrap in a lazy module.

@NgModule({imports: [NgbModalModule]})

This library has a NgbModal service provided in root.

@Injectable({providedIn: 'root'})
class NgbModal {...}

I inject it into a component.

constructor(private modal: NgbModal) {}

I develop a class extension of that one.

export class CustomNgbModal extends NgbModal{...}

How can I override NgbModal type with CustomNgbModal?

Using modules will be

{provide: NgbModal, useClass: CustomNgbModal}

but using providedIn root metadata, no clue.

So, how can I override a module which is provided in root?

like image 588
Serginho Avatar asked Jan 19 '26 06:01

Serginho


1 Answers

create some static function forFeature() (like "useCustom")

@NgModule({
  // the default provider
  providers: [NgbModal]
})
export class NgbModalModule {
  static useCustom(): ModuleWithProviders<NgbModalModule> {
    return {
      ngModule: NgbModalModule,
      providers: [
        {provide: NgbModal, useClass: CustomNgbModal}
      ]
    };
  }
}

then when importing this module to another do it this way:

@NgModule({
  // import it using the static function
  imports: [NgbModalModule.useCustom()]
})
export class AnotherModule { }
like image 112
David Filipe Lopes Domingues Avatar answered Jan 21 '26 18:01

David Filipe Lopes Domingues



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!