Sub topic 12
Changing the lookup with optional, self, skipSelf and host
This chapter assumes you know how inject() works, how providers are declared on components, routes and the root, and the order in which Angular searches element injectors and then environment injectors. Here you will learn four options that change that search: optional, self, skipSelf and host.
The default lookup and why you would change it
By default, inject(Token) starts at the element injector of the current node and walks up the component tree. It then continues through the environment injectors. If nothing provides the token, Angular throws NullInjectorError.
That default fits most code. Sometimes you need something different:
- The provider may legitimately be missing, and you want a fallback instead of a crash.
- You need the instance from this exact node, not an ancestor's.
- You need the ancestor's instance because the node's own provider is being created.
- You want to stop the search at the boundary of the current component.
Each option below addresses one of these cases.
The four options
| Option | Effect on the lookup | Failure behavior |
|---|---|---|
| `optional` | Does not change where Angular looks | Returns `null` instead of throwing |
| `self` | Looks only in the current node's injector | Throws, or returns `null` with `optional` |
| `skipSelf` | Starts at the parent node and ignores the current node | Throws, or returns `null` with `optional` |
| `host` | Stops at the host element of the current component | Throws, or returns `null` with `optional` |
optional is the only option that changes the failure behavior. The other three restrict the search range. They can therefore turn a successful lookup into a failure, and that is why they are so often paired with optional.
With inject(), you pass the options as an object:
import { inject } from '@angular/core';
import { ThemeService } from './theme.service';
const a = inject(ThemeService, { optional: true }); // ThemeService | null
const b = inject(ThemeService, { self: true }); // ThemeService
const c = inject(ThemeService, { skipSelf: true }); // ThemeService
const d = inject(ThemeService, { host: true, optional: true }); // ThemeService | nullThe return type matters. TypeScript infers T | null only when optional: true is present, so you must handle null explicitly.
Constructor injection uses decorators for the same purpose: @Optional(), @Self(), @SkipSelf() and @Host(). They have the same meaning. New code usually prefers the inject() options because they type the result correctly and work in field initializers.
optional: a provider that may not exist
Use optional when the dependency is an enhancement, not a requirement. A component might adapt itself if a theme service exists and use defaults if it does not:
import { Component, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-badge',
standalone: true,
template: `<span [class]="cssClass">badge</span>`,
})
export class BadgeComponent {
private readonly theme = inject(ThemeService, { optional: true });
protected readonly cssClass = this.theme ? this.theme.badgeClass : 'badge-default';
}Do not use optional to hide a configuration mistake. If the service is required, a NullInjectorError at startup is more useful than a null that fails later in a template.
self: only this node
self limits the search to the injector of the current node. For a component, that node is the component's host element in the parent's template. This option answers the question "did this node provide its own instance?"
It is useful when a component declares providers and wants to be sure it is not using an ancestor's copy. It is also useful when a directive should only react to a provider placed on the same element. If no provider is declared on that node, the lookup fails, even when an ancestor provides the token.
skipSelf: start from the parent
skipSelf ignores the current node and starts at the parent. This is how a service or component with its own provider can still reach the instance above it. The common case is a recursive structure such as a tree or nested menus, where each level needs to know about the level above.
import { Component, Injectable, inject } from '@angular/core';
@Injectable()
export class LevelService {
private readonly parent = inject(LevelService, { skipSelf: true, optional: true });
readonly depth: number = this.parent ? this.parent.depth + 1 : 0;
}
@Component({
selector: 'app-level',
standalone: true,
providers: [LevelService],
template: `<p>Depth {{ level.depth }}</p><ng-content />`,
})
export class LevelComponent {
protected readonly level = inject(LevelService);
}Each app-level element creates its own LevelService. When that service is constructed, skipSelf makes it look above the current element. This avoids the service finding itself. The outermost level finds no parent, so optional gives null and the depth is 0. A level nested inside it finds the outer service and gets depth 1.
Without skipSelf, inject(LevelService) inside LevelService would resolve against the node's own provider, which is the very instance being created. That is a circular dependency.
Combining self and skipSelf with the same token
The example from the plan shows the two options side by side:
import { Component, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Component({
selector: 'app-themed-panel',
standalone: true,
providers: [ThemeService],
template: `<ng-content />`,
})
export class ThemedPanelComponent {
private readonly ownTheme = inject(ThemeService, { self: true });
private readonly parentTheme = inject(ThemeService, { skipSelf: true, optional: true });
}ownTheme is the instance created by this component's providers entry. parentTheme is whatever an ancestor provides, or null when no ancestor does. Together they let a component compare, merge or inherit settings from the enclosing context.
Do not set self and skipSelf in the same call. They exclude each other: one allows only this node and the other excludes it.
host: stop at the component boundary
host limits the search to the host element of the component whose template contains the requesting node. Angular searches up to and including that host element, then stops.
The lookup rule is easiest to follow in a diagram.
Suppose a directive sits in a component's template and asks for a service with host: true. It can find providers on its own element and on the component host element, including that component's viewProviders. It cannot see providers on elements above the host. It also does not continue into the environment injectors. The point is to depend only on what the component author controls.
import { Directive, inject } from '@angular/core';
import { ThemeService } from './theme.service';
@Directive({
selector: '[appThemeAware]',
standalone: true,
})
export class ThemeAwareDirective {
private readonly theme = inject(ThemeService, { host: true, optional: true });
}If a page-level ancestor provides ThemeService but the component hosting this directive does not, theme is null.
This also explains the link to viewProviders. Providers listed there are visible to the component's own view and, through host, to nodes inside that view. They are not visible to projected content. A host lookup from a projected child therefore does not reach the host component's viewProviders.
Quick decision guide
- The dependency is optional and a missing value is fine: use
optional. - You want the instance declared on this exact node: use
self. - A node provides a token and also needs the ancestor's instance of it: use
skipSelf, usually withoptionalfor the top level. - A reusable piece should depend only on its host component's own providers: use
host.
Common mistakes
- Using
optionalwithout handlingnull. The compiler will flag it, but a non-null assertion (!) removes the protection. - Using
selfon a service declared withprovidedIn: 'root'. No element injector holds it, so the lookup fails. - Forgetting that
skipSelfstill searches upward. It does not guarantee the result comes from the immediate parent. It comes from the nearest ancestor that provides the token. - Expecting
hostto behave likeself.hostincludes the host element and, with it, the host component'sviewProviders.
Exercise
A RowComponent lists providers: [RowContext]. Inside RowContext, you write inject(RowContext) to find the enclosing row's context for nested rows. What goes wrong, and how do you fix it?
Show answer
The lookup starts at the node that is creating the service, so it finds its own provider and creates a circular dependency. Use inject(RowContext, { skipSelf: true, optional: true }). skipSelf starts at the parent node, and optional returns null for the outermost row.
Exercise
A directive uses inject(ThemeService, { host: true, optional: true }). A page-level component provides ThemeService, but the component whose template contains the directive does not. What does the directive receive?
Show answer
It receives null. The host option stops the search at the host element of the component that contains the directive, so providers on elements above that host are not considered.