inject • Angular
@paramtokenProviderToken<T>
A token that represents a dependency that should be injected.
@returnsT
the injected value if operation is successful, null otherwise.
@paramtokenProviderToken<T>
A token that represents a dependency that should be injected.
@paramoptionsInjectOptions & { optional?: false | undefined; }
Control how injection is executed. Options correspond to injection strategies
that can be specified with parameter decorators @Host, @Self, @SkipSelf, and
@Optional.
@returnsT
the injected value if operation is successful.
@paramtokenProviderToken<T>
A token that represents a dependency that should be injected.
@returnsT | null
the injected value if operation is successful, null if the token is not
found and optional injection has been requested.
@paramtokenHostAttributeToken
A token that represents a static attribute on the host node that should be injected.
@returnsstring
Value of the attribute if it exists.
@paramtokenHostAttributeToken
A token that represents a static attribute on the host node that should be injected.
@paramoptions{ optional: true; }
@returnsstring | null
Value of the attribute if it exists, otherwise null.
@paramtokenHostAttributeToken
A token that represents a static attribute on the host node that should be injected.
@paramoptions{ optional: false; }
@returnsstring
Value of the attribute if it exists.
Usage Notes
In practice the inject() calls are allowed in a constructor, a constructor parameter and a
field initializer:
@Injectable({providedIn: 'root'})
export class Car {
radio: Radio|undefined;
// OK: field initializer
spareTyre = inject(Tyre);
constructor() {
// OK: constructor body
this.radio = inject(Radio);
}
}
It is also legal to call inject from a provider's factory:
providers: [
{provide: Car, useFactory: () => {
// OK: a class factory
const engine = inject(Engine);
return new Car(engine);
}}
]
Calls to the inject() function outside of the class creation context will result in error. Most
notably, calls to inject() are disallowed after a class instance was created, in methods
(including lifecycle hooks):