angularangular-dependency-injection

How to pass a default value with @Optional in Angular 20?


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){}

Solution

  • 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.