Sub topic 11
Controlling Resolution with optional, self, skipSelf, and host
By default, Angular resolves a dependency by starting at the requesting element's injector and walking up. It checks each element injector, then the environment injectors, and throws if no injector has a provider. Resolution modifiers change that walk. They can change where the search starts, where it stops, and what happens when nothing is found.
This chapter assumes you already know how inject() and constructor injection work, how providers are registered, and how element and environment injectors form a hierarchy, as covered in the earlier chapters on the injector hierarchy and component-scoped services. You should also be comfortable reading standalone components and directives.
The four modifiers at a glance
Each modifier is an option passed as the second argument to inject(). Each also has a matching parameter decorator for constructor injection.
| Option for `inject()` | Constructor decorator | Effect on the search | When nothing is found |
|---|---|---|---|
| `optional: true` | `@Optional()` | Does not change the search path | Returns `null` instead of throwing |
| `self: true` | `@Self()` | Checks only the current element's injector | Throws (unless also optional) |
| `skipSelf: true` | `@SkipSelf()` | Starts at the parent injector | Throws (unless also optional) |
| `host: true` | `@Host()` | Stops at the host element of the current component view | Throws (unless also optional) |
optional controls the failure behavior. The other three control the search boundary. You will often combine optional with one of the others.
optional: tolerate a missing provider
Without optional, a missing provider throws NG0201: No provider for X found. With optional: true, inject() returns null. The TypeScript return type becomes T | null, so the compiler makes you handle the missing case.
import { Component, InjectionToken, inject } from '@angular/core';
export interface Analytics {
track(event: string): void;
}
export const ANALYTICS = new InjectionToken<Analytics>('ANALYTICS');
@Component({
selector: 'app-buy-button',
standalone: true,
template: `<button (click)="buy()">Buy</button>`
})
export class BuyButtonComponent {
private readonly analytics = inject(ANALYTICS, { optional: true });
buy(): void {
this.analytics?.track('buy_clicked');
}
}This suits plug-in features such as analytics, feature flags, or an optional parent context, where an app can choose not to provide them.
A token created with a factory in its InjectionToken options always resolves, because the factory acts as a root-level default. Adding optional to such a token has no visible effect unless a modifier like self or host blocks the search before it reaches the root.
self: only look here
self: true restricts the lookup to the injector of the element that is asking. For a component or directive, that injector holds the providers declared on that element: the component's providers and viewProviders, and the providers of any directive on the same element.
import { Component, Injectable, inject } from '@angular/core';
@Injectable()
export class FormDraftService {
value = '';
}
@Component({
selector: 'app-editor',
standalone: true,
providers: [FormDraftService],
template: `<textarea [value]="draft.value"></textarea>`
})
export class EditorComponent {
// Guaranteed to be this editor's own instance, never an ancestor's.
protected readonly draft = inject(FormDraftService, { self: true });
}If someone later deletes providers: [FormDraftService], the default lookup would quietly find an ancestor's instance, and two editors would share a draft. With self: true, the component throws right away, so the mistake shows up at once.
Gotcha: self does not reach environment injectors
self and host both stop the search before the environment injectors. A service that uses providedIn: 'root' is therefore not visible to inject(X, { self: true }) in a component:
import { Component, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ThemeService {
mode = 'light';
}
@Component({
selector: 'app-header',
standalone: true,
template: `{{ theme?.mode }}`
})
export class HeaderComponent {
// null: the root provider is outside the element injector being checked.
protected readonly theme = inject(ThemeService, { self: true, optional: true });
}This often surprises people who expect self to mean "the nearest instance". It actually means "this element's injector only".
skipSelf: start at the parent
skipSelf: true ignores the current injector and starts the search one level up. It has two common uses.
Recursive structures
A tree node component often needs its parent node. Asking for its own class without skipSelf would return itself, because a component is always resolvable from its own element injector.
import { Component, Input, inject } from '@angular/core';
@Component({
selector: 'app-tree-node',
standalone: true,
template: `
<span>{{ label }} (depth {{ depth }})</span>
<ng-content />
`
})
export class TreeNodeComponent {
@Input() label = '';
private readonly parent = inject(TreeNodeComponent, { skipSelf: true, optional: true });
get depth(): number {
return this.parent ? this.parent.depth + 1 : 0;
}
}Used like this, the inner node reports depth 1:
<app-tree-node label="root">
<app-tree-node label="child" />
</app-tree-node>optional is required here because the outermost node has no parent node.
Guarding against duplicate instances
A service that must exist only once can check whether an ancestor injector already holds an instance:
import { Injectable, inject } from '@angular/core';
@Injectable()
export class SessionService {
constructor() {
const existing = inject(SessionService, { skipSelf: true, optional: true });
if (existing) {
throw new Error('SessionService is already provided by an ancestor injector.');
}
}
}This works because the constructor runs in an injection context, and skipSelf begins at the parent of whichever injector is creating the service.
Gotcha: skipSelf inside environment injectors
skipSelf always means the parent of the injector doing the resolving. In a component, the parent is the parent element injector. In a service created by the root injector, the parent is the platform injector. A root service that calls inject(Other, { skipSelf: true }) for another root service will fail, because the platform injector does not hold application-level providers.
host: stop at the view boundary
host: true lets the search climb element injectors but stops at the host element of the component whose template declares the requester. It never continues into ancestor views or environment injectors.
This lets a directive say: "I depend on something provided by the component whose template I'm used in, and nothing further out."
import { Component, Directive, Injectable, inject } from '@angular/core';
@Injectable()
export class FieldRegistry {
readonly names: string[] = [];
register(name: string): void {
this.names.push(name);
}
}
@Directive({
selector: '[appField]',
standalone: true
})
export class FieldDirective {
private readonly registry = inject(FieldRegistry, { host: true });
constructor() {
this.registry.register('field');
}
}
@Component({
selector: 'app-signup-form',
standalone: true,
imports: [FieldDirective],
viewProviders: [FieldRegistry],
template: `
<input appField name="email" />
<input appField name="password" />
<p>Registered: {{ registry.names.length }}</p>
`
})
export class SignupFormComponent {
protected readonly registry = inject(FieldRegistry);
}Each FieldDirective climbs from its <input> to the app-signup-form host element, finds the viewProviders entry, and stops. If you use appField in another component that has no FieldRegistry, it throws. It will not pick up a registry from some outer form by accident.
Gotcha: content projection and host
Projected content belongs to the view of the component that wrote it, not to the component that receives it. A directive inside <ng-content> projected into app-signup-form reaches its host boundary at the component that declared it. It does not see SignupFormComponent's viewProviders. Element-level providers on app-signup-form sit outside the declaring component's view, so host cannot see them either. Use host only when the requester and the provider share a template.
Combining modifiers
| Combination | Meaning | Typical use |
|---|---|---|
| `{ skipSelf: true, optional: true }` | Nearest ancestor instance, or `null` | Parent lookup in recursive components, duplicate guards |
| `{ self: true, optional: true }` | This element's instance, or `null` | Directive that cooperates with an optional sibling directive |
| `{ host: true, optional: true }` | Instance from the current view, or `null` | Directive that improves when a container is present |
| `{ skipSelf: true, host: true }` | Ancestor within the view, excluding self | Nested directives of the same type inside one template |
Do not combine self with skipSelf. The two options contradict each other, and Angular rejects or ignores the request depending on context.
Constructor decorator equivalents
The decorators map one-to-one onto the options. Stack them on a parameter:
import { Component, Optional, SkipSelf } from '@angular/core';
@Component({
selector: 'app-tree-node-legacy',
standalone: true,
template: `<ng-content />`
})
export class TreeNodeLegacyComponent {
constructor(@Optional() @SkipSelf() private readonly parent: TreeNodeLegacyComponent | null) {}
}Decorator order does not matter. Type the parameter as T | null whenever @Optional() is present. The decorator does not change the type for you, unlike the inject() overload.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| NG0201 with `self: true` on a root service | `self` never checks environment injectors | Remove `self`, or provide the service on the element |
| Child component gets itself instead of the parent | Missing `skipSelf` when injecting its own class | Add `skipSelf: true` |
| Directive with `host: true` works in one template but not another | The provider is in `providers` on an outer element, or the directive is projected | Move the provider into the declaring component's `viewProviders` or `providers` |
| Value is unexpectedly `null` | `optional` hid a missing provider | Remove `optional` temporarily to see the NG0201 error |
| `skipSelf` in a root service throws | Parent of the root injector is the platform injector | Drop `skipSelf` or redesign the dependency |
Exercise
A component declares providers: [ThemeService] and its child component calls inject(ThemeService, { self: true }). ThemeService also has providedIn: 'root'. What does the child receive?
Show answer
It throws NG0201. The self option checks only the child's own element injector, which has no ThemeService provider. The search never reaches the parent's providers or the root injector.
Exercise
In a recursive TreeNodeComponent, why must the parent lookup use both skipSelf and optional?
Show answer
Without skipSelf, the lookup finds the component's own instance, because every component can be resolved from its own element injector. Without optional, the outermost node throws, because it has no ancestor TreeNodeComponent.
Exercise
A FieldDirective uses inject(FieldRegistry, { host: true }). It works inside SignupFormComponent's template, but it throws when the same input is projected into SignupFormComponent through ng-content from a parent page. Why?
Show answer
Projected content belongs to the view of the parent page that declared it. The host boundary therefore stops at the parent page's host element, and the search never sees SignupFormComponent's viewProviders. FieldRegistry has to be provided within the declaring component's view.