Cookies concent notice

This site uses cookies from Google to deliver its services and to analyze traffic.
Learn more
Skip to main content
This site is no longer updated.Head to Angular.devHome
/

This is the archived documentation for Angular v17. Please visit angular.dev to see this page for the current version of Angular.

Optional

Parameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. The DI framework provides null if the dependency is not found.

See more...

See also

Description

Can be used together with other parameter decorators that modify how dependency injection operates.

Further information is available in the Usage Notes...

Options

Usage notes

The following code allows the possibility of a null result:

      
      class Engine {}

@Injectable()
class Car {
  constructor(@Optional() public engine: Engine) {}
}

const injector = Injector.create({
  providers: [{provide: Car, deps: [[new Optional(), Engine]]}],
});
expect(injector.get(Car).engine).toBeNull();