Sub topic 11
Controlling Resolution with optional, self, skipSelf, and host
This chapter assumes you know the element and environment injector hierarchy from the previous chapters. You should also know how to inject a service with inject() and how to list services in a component's providers array.
The default lookup
When you call inject(Token), Angular starts at the element injector of the current component or directive. If that injector has no provider for the token, Angular moves up through the ancestor elements. If no element injector has a provider, Angular checks the environment injectors, ending at the root injector. If none of them has a provider, Angular throws NullInjectorError.
Resolution modifiers change where this search starts, where it stops, and what happens when it finds nothing. You pass them as the second argument to inject().
The four options
| Option | Effect | Typical use |
|---|---|---|
| `optional: true` | Returns `null` when nothing is found instead of throwing | Features that work with or without a dependency |
| `self: true` | Searches only the current element injector | Requiring something on the same element, such as a form control directive |
| `skipSelf: true` | Starts the search at the parent element | Finding an ancestor of the same type |
| `host: true` | Stops at the host component's element | Keeping a directive from reaching outside its component's view |
When you use optional: true, TypeScript gives the return type as T | null, so the compiler makes you handle the missing case.
Finding a parent of the same type with skipSelf
A nested panel needs to know how deep it sits. Every panel injects the nearest ancestor PanelComponent. A component instance is available as a token in its own element injector. That means a panel that injected PanelComponent without skipSelf would ask for itself, and Angular would report a circular dependency.
import { Component, inject } from '@angular/core';
@Component({
selector: 'app-panel',
standalone: true,
template: `<div [style.paddingLeft.px]="depth * 16">Depth {{ depth }}<ng-content /></div>`
})
export class PanelComponent {
private readonly parent = inject(PanelComponent, { skipSelf: true, optional: true });
readonly depth: number = this.parent ? this.parent.depth + 1 : 0;
}With <app-panel><app-panel></app-panel></app-panel>, the outer panel gets null and depth 0. The inner panel gets the outer panel and depth 1. Without optional: true, the outermost panel would throw.
Restricting to the same element with self
A directive that adds behavior to form inputs should only use a control on its own element. It should never pick up one from an ancestor.
import { Directive, inject } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appTrim]',
standalone: true,
host: { '(blur)': 'trim()' }
})
export class TrimDirective {
private readonly control = inject(NgControl, { self: true, optional: true });
trim(): void {
const value = this.control?.value;
if (typeof value === 'string') {
this.control?.control?.setValue(value.trim());
}
}
}The host boundary
host: true lets the search climb through element injectors but stops at the host element of the current component's view. A directive used inside a component's template can then see providers declared by that component, including its viewProviders. It cannot see providers from the components further up. Use host when a directive belongs to one component and must not depend on whatever happens to sit above it.
Constructor decorator equivalents
With constructor injection, you get the same options from parameter decorators.
import { Component, Optional, SkipSelf } from '@angular/core';
import { FormDraftService } from './form-draft.service';
@Component({ selector: 'app-child-editor', standalone: true, template: '' })
export class ChildEditorComponent {
constructor(@Optional() @SkipSelf() readonly parentDraft: FormDraftService | null) {}
}The other decorators are @Self() and @Host(). These decorators still work, but new code normally uses the inject() options.
Common errors
- Using
selforskipSelfwithoutoptional, then getting aNullInjectorErrorin the one place where no provider exists. - Expecting
selfto find aprovidedIn: 'root'service.selfnever reaches the environment injectors. - Combining
selfandskipSelf. The two options contradict each other, and Angular reports an error.
Exercise
A directive calls inject(ThemeService, { self: true }). ThemeService uses @Injectable({ providedIn: 'root' }), and no element lists it in providers. What happens, and how would you make the directive get the root instance?
Show answer
Angular throws NullInjectorError, because self limits the search to the directive's own element injector and never reaches the root environment injector. Remove the self option, which restores the default search that ends at the root injector, or add optional: true if a null result is acceptable.
Exercise
Why does PanelComponent need both skipSelf and optional to inject its parent panel?
Show answer
Without skipSelf, the panel would find itself in its own element injector, which causes a circular dependency. Without optional, the outermost panel would throw because it has no ancestor panel; with optional it receives null.