0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.