This is the archived documentation for Angular v5. Please visit angular.io to see documentation for the current version of Angular.

Optional

npm Package @angular/core
Module import { Optional } from '@angular/core';
Source core/src/di/metadata.ts

A parameter metadata that marks a dependency as optional. Injector provides null if the dependency is not found.

How To Use

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

Description

For more details, see the "Dependency Injection Guide".

Example

      
      class Engine {}

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

const injector = ReflectiveInjector.resolveAndCreate([Car]);
expect(injector.get(Car).engine).toBeNull();