Skip to content

The inject() Function

inject() retrieves a dependency from the current injector without going through the constructor:

@Component({ /* ... */ })
export class OrderDetail {
private readonly api = inject(OrderApiClient);
private readonly route = inject(ActivatedRoute);
}

It is not merely shorter than constructor injection. It works in places a constructor cannot reach — functional guards, resolvers, interceptors, provider factories — and it removes an entire category of inheritance friction. For the DI system it sits on, see Dependency Injection in Angular.

inject() requires an injection context — a runtime state in which Angular has set the current injector. You are in one:

  • During the constructor of a DI-instantiated class (@Component, @Directive, @Injectable, @Service).
  • In field initialisers of such classes.
  • In a useFactory function of a provider or @Injectable.
  • In the factory of an InjectionToken or a @Service.
  • In any stack frame running inside an injection context.

That last item is why functional router APIs work:

export const authGuard: CanActivateFn = (route, state) =>
inject(AuthService).canActivate(state.url);
export const orderResolver: ResolveFn<Order> = (route) =>
inject(OrderApiClient).getOrder(route.paramMap.get('id')!);
export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) {
const token = inject(AuthService).getAuthToken();
return next(req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`) }));
}

Angular runs each of these inside an injection context deliberately, which is what let guards, resolvers and interceptors stop being classes.

export class OrderDetail {
private readonly api = inject(OrderApiClient); // fine — field initialiser
ngOnInit(): void {
const logger = inject(Logger); // NG0203
}
onSave(): void {
const audit = inject(AuditService); // NG0203
}
async load(): Promise<void> {
const data = await this.api.list();
const cache = inject(CacheService); // NG0203 — after an await
}
}

Lifecycle hooks, event handlers, timer callbacks, and anything after an await are not injection contexts. The context is established synchronously and unwound when the synchronous portion returns.

The fix is almost always to move the call to a field initialiser. Field initialisers run during construction, so anything you need later can be captured there.

Inheritance stops being painful. With constructor injection, a subclass must repeat every one of the base class’s dependencies in its own super() call, and adding a dependency to the base class is a breaking change for every subclass:

// Constructor injection — the subclass must know and forward everything.
abstract class BaseList {
constructor(protected api: ApiClient, protected logger: Logger) {}
}
class OrderList extends BaseList {
constructor(api: ApiClient, logger: Logger, private router: Router) {
super(api, logger);
}
}
// inject() — the base class owns its own dependencies.
abstract class BaseList {
protected readonly api = inject(ApiClient);
protected readonly logger = inject(Logger);
}
class OrderList extends BaseList {
private readonly router = inject(Router);
}

It works in functions, which is what made functional guards, resolvers and interceptors possible at all.

It composes into helpers — see below.

It avoids useDefineForClassFields friction. Under modern TypeScript class-field semantics, constructor parameter properties and field initialisers interact in ways that surprise people; inject() in a field initialiser sidesteps it.

Constructor injection is still fully supported and is not deprecated. Use it when a base class you do not control requires it, or when a team standard calls for it — but new code has no strong reason to prefer it.

readonly parentTheme = inject(ThemeService, { skipSelf: true });
readonly maybeForm = inject(NgControl, { optional: true });
readonly ownConfig = inject(PanelConfig, { self: true, optional: true });
readonly bounded = inject(TooltipHost, { host: true, optional: true });
Option Effect
optional: true Return null instead of throwing when not found
self: true Look only at the current element’s injector
skipSelf: true Start at the parent injector
host: true Stop searching at the host component

They combine except for host + self and skipSelf + self. optional narrows the return type to include null, so TypeScript makes you handle it.

Because inject() is a function, you can compose it. This is one of its most underused capabilities:

export function injectDestroyed$(): Observable<void> {
const subject = new Subject<void>();
inject(DestroyRef).onDestroy(() => {
subject.next();
subject.complete();
});
return subject.asObservable();
}
export function injectRouteParam(name: string): Signal<string | null> {
const route = inject(ActivatedRoute);
return toSignal(route.paramMap.pipe(map((p) => p.get(name))), { initialValue: null });
}
export class OrderDetail {
private readonly orderId = injectRouteParam('id');
}

Assert the precondition in any helper you share, so a caller who invokes it from ngOnInit gets a message naming your function rather than a generic DI error:

export function injectNativeElement<T extends Element>(): T {
assertInInjectionContext(injectNativeElement);
return inject(ElementRef).nativeElement;
}

Without that assert, a shared helper is a booby trap.

When code genuinely must run in a context later, capture an injector and re-enter:

@Service()
export class ReportRunner {
private readonly injector = inject(EnvironmentInjector);
run(): void {
runInInjectionContext(this.injector, () => {
inject(ReportExporter).export();
});
}
}

Use it sparingly. Nine times in ten, capturing the dependency in a field is simpler and clearer. Its genuine homes are dynamically created components and library code that runs user-supplied callbacks.

Several APIs that normally require an injection context accept an explicit injector option instead, which is usually the better tool:

effect(() => console.log(this.count()), { injector: this.injector });
toSignal(this.source$, { injector: this.injector });

inject() reads a module-level “current injector” pointer that Angular sets before constructing a class or invoking a context-aware callback, and restores afterwards. Two things follow:

This is why await breaks it. The pointer is restored when the synchronous portion returns, long before the continuation runs. Nothing about the failure is specific to promises — any deferred callback is outside the context for the same reason.

This is why inject() cannot be dynamic in the way people expect. It resolves against whichever injector is current at the moment of the call, so calling it from a different context yields a different injector — or none.

Mistake Error / consequence Fix
inject() in ngOnInit or an event handler NG0203 Move to a field initialiser
inject() after an await NG0203 Inject before the first await
inject() in a plain (non-DI) class NG0203 Provide the class through DI, or pass dependencies in
Shared helper without assertInInjectionContext Confusing generic DI error for callers Add the assert
runInInjectionContext used routinely Indirection with no benefit Capture the dependency in a field
Mixing inject() and constructor params in one class Two conventions; confusing initialisation order Pick one per class
inject() for something that is not a dependency DI used as a service locator Pass values as inputs or parameters
Assuming optional: true returns undefined It returns null Check for null
Terminal window
ng generate @angular/core:inject

The schematic converts constructor injection to inject() across a project. Review the diff on classes with inheritance or unusual initialisation order — field initialisers run in declaration order, so a field that depends on another must come after it.