Last active
October 5, 2023 13:54
-
-
Save gentoo90/85b8bb2b9186b7b9317507b1fffe8d37 to your computer and use it in GitHub Desktop.
How to extend provided value in Angular DI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Nice little trick that allows to provide some settings in the parent | |
* and then override some of them in the child | |
*/ | |
import { Component, Inject, InjectionToken, NgModule, SkipSelf } from '@angular/core'; | |
import { defaults } from 'lodash-es'; | |
export const SETTINGS_TOKEN = new InjectionToken('SETTINGS_TOKEN'); | |
@Component({ | |
selector: 'app-example', | |
template: '', | |
providers: [ | |
{ | |
provide: SETTINGS_TOKEN, | |
useFactory: (defaultSettings: Record<string, number>) => { | |
return defaults({ a: 10 }, defaultSettings); | |
}, | |
deps: [[new SkipSelf(), SETTINGS_TOKEN]] | |
} | |
] | |
}) | |
export class ExampleComponent { | |
constructor(@Inject(SETTINGS_TOKEN) private settings: Record<string, number>) {} | |
} | |
@NgModule({ | |
declarations: [ExampleComponent], | |
exports: [ExampleComponent], | |
providers: [ | |
{ | |
provide: SETTINGS_TOKEN, | |
useValue: { | |
a: 1, | |
b: 2, | |
c: 3 | |
} | |
} | |
] | |
}) | |
export class ExampleModule {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment