@Optional
This is the documentation for Angular 6.
You can switch to the latest version Angular 10.
You can switch to the latest version Angular 10.
A constructor parameter decorator that marks a dependency as optional.
constructor(@Optional() service: Service) {}
Example
The DI framework provides null if the dependency is not found. For example, the following code allows the possibility of a null result:
class Engine {}
@Injectable()
class Car {
constructor(@Optional() public engine: Engine) {}
}
const injector = ReflectiveInjector.resolveAndCreate([Car]);
expect(injector.get(Car).engine).toBeNull();