In Angular 20, how can we inject an optional InjectionToken
with a default value?
In Angular <20, I used to do it as follows:
constructor(@Optional@Inject(FOO) private foo = true){}
With DI using the inject
function this is quite straightforward:
export class MyComponent {
config = inject(FOO, { optional: true }) ?? true;
}
Note: thanks to JSON Derulo for their answer on GitHub.