← Back to Angular, page 7

angular-0124 · Medium mid

What do the optional, self, skipSelf and host options of inject() do, and when do you need them?

By default, inject looks up the injector tree and throws if it finds nothing. optional returns null instead of throwing, self searches only the current injector, skipSelf starts at the parent, and host stops the search at the host component. They give precise control in nested components and directives.

Full answer

Angular looks for a provider in the element injector of the current component, then up through parent elements, then in the environment injectors (route, root, platform). The inject(Token, options) flags change this search.

  • optional: true: if no provider is found, return null instead of throwing NullInjectorError. Use it for dependencies that may not exist, such as a parent component or an optional configuration.
  • self: true: look only in the current element's injector (the component or directive itself). If it is not provided there, fail (or return null with optional). Use it to require that a directive has its own provider.
  • skipSelf: true: start looking at the parent injector. Use it when a service wants to find another instance of itself above it, for example a nested tree node that needs its parent node's service.
  • host: true: stop the search at the host element of the current component's template. Content projected from outside is not searched beyond the host. It is useful for directives that must only link to a provider inside the same component, and it is common in form controls.

Older constructor style used decorators with the same names: @Optional(), @Self(), @SkipSelf(), @Host(). The inject options replace them with a more flexible and type-safe syntax. With optional: true the return type becomes T | null.

Common cases:

  1. Recursive components: each tree node provides a NodeService. Inside, inject(NodeService, { skipSelf: true, optional: true }) finds the parent node's service, and the root node gets null.
  2. Optional features: inject(LoggerService, { optional: true }) so a library works without a logger.
  3. Preventing accidental sharing: { self: true } makes the directive fail loudly if it was not given its own state.

Combine flags: { self: true, optional: true } means "only mine, and null if absent".

typescript
import { Component, Injectable, inject, input } from '@angular/core';

@Injectable()
export class NodeService {
  // Finds the parent node's service. The root node gets null.
  readonly parent = inject(NodeService, { skipSelf: true, optional: true });

  get depth(): number {
    return this.parent ? this.parent.depth + 1 : 0;
  }
}

@Component({
  selector: 'app-tree-node',
  providers: [NodeService], // each node has its own service
  template: `
    <div>{{ name() }} (depth {{ service.depth }}, parent {{ service.parent ? 'yes' : 'none' }})</div>
    <ng-content />
  `,
})
export class TreeNodeComponent {
  readonly name = input.required<string>();
  protected readonly service = inject(NodeService, { self: true });
}

@Component({
  selector: 'app-tree',
  imports: [TreeNodeComponent],
  template: `
    <app-tree-node name="root">
      <app-tree-node name="child">
        <app-tree-node name="grandchild" />
      </app-tree-node>
    </app-tree-node>
  `,
})
export class TreeComponent {}

Angular 20.3, strict template check passes. A Karma test builds a three level tree and checks the depth and the parent of each node.

Key points

  • `optional` returns null instead of throwing. `self` limits to the current injector.
  • `skipSelf` starts from the parent. `host` stops at the host component.
  • Recursive components use `skipSelf` and `optional` to find their parent.
  • The `inject` options replace the old decorators.

Common mistakes

  • Forgetting `optional` and getting `NullInjectorError` for an optional dependency.
  • Using `skipSelf` at the root, where no parent exists, without `optional`.
  • Assuming flags apply to environment injectors as they do to element injectors.

Follow-ups

  • How would a tree node find the root of the tree?
  • What does the injector search order look like for a directive on a component?
  • How do `viewProviders` interact with `host`?

Tips

  • Use the recursive tree example. It shows skipSelf and optional together.
  • Mention the return type becomes nullable.
  • Give the old decorator names so you can read legacy code.

Evaluation rubric

  • Explains each flag correctly.
  • Gives at least one realistic example.
  • Knows the legacy decorator equivalents.