← Back to Angular, page 3

angular-0041 · Hard senior

How does Angular's injector hierarchy work, and how do inject() options (self, skipSelf, optional, host), viewProviders and runInInjectionContext behave?

Angular has two injector trees. The environment injector tree (root, route and module level) and the element injector tree (components and directives in the DOM structure). A lookup starts at the element injector, walks up the elements, then moves to the environment injectors. Options such as self, skipSelf, optional, and host restrict the walk, and runInInjectionContext lets plain functions call inject().

Full answer

When code asks for a token, Angular first checks the element injector of the current component or directive, then each parent element up to the root of the view, and then the environment injectors: route-level injectors for routes with providers, then the root injector, then the platform injector. The first match wins. If nothing matches, an error (NullInjectorError) is thrown, unless optional: true is set.

Where providers are placed:

  • providers on a component or directive: available to the component, its view, and its projected content children.
  • viewProviders on a component: available only to the component's own view children, not to projected content. Useful for hiding an implementation detail from content that users project in.
  • providedIn: 'root' or ApplicationConfig.providers: the root environment injector, one instance.
  • Route providers: a new environment injector for that route tree.

Options for inject(Token, { ... }) (or the older @Self, @SkipSelf, @Optional, @Host decorators):

  • optional: true: return null instead of throwing.
  • self: true: only look at this element's own injector.
  • skipSelf: true: start looking at the parent, which is how a component can find its own parent instance of the same type, such as a nested menu.
  • host: true: stop the search at the host element of the current component view.

runInInjectionContext(injector, fn) runs fn in a context where inject() is allowed. Use it for helper functions or a test. The EnvironmentInjector lets you do this outside a constructor. If you call inject() in a random method, Angular throws NG0203.

Edge case: a service provided at component level has the same lifetime as the component. Any service that must be shared across components must be provided higher up.

typescript
import {
  Component,
  EnvironmentInjector,
  Injectable,
  inject,
  runInInjectionContext,
  signal,
} from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-tab-group',
  template: `<ng-content />`,
})
export class TabGroupComponent {
  readonly active = signal('');
}

@Component({
  selector: 'app-tab',
  template: `<button (click)="select()">{{ name }}</button>`,
})
export class TabComponent {
  name = 'Tab';
  // Found through the element injector. optional: true allows use outside a group.
  private readonly group = inject(TabGroupComponent, { optional: true });

  select(): void {
    this.group?.active.set(this.name);
  }
}

@Injectable()
export class MenuState {
  // Looks for a MenuState on a parent element, skipping this component's own.
  readonly parent = inject(MenuState, { skipSelf: true, optional: true });

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

@Component({
  selector: 'app-menu',
  providers: [MenuState],
  template: `<p>Menu depth {{ state.depth() }}</p><ng-content />`,
})
export class MenuComponent {
  protected readonly state = inject(MenuState);
}

@Injectable({ providedIn: 'root' })
export class Helper {
  private readonly env = inject(EnvironmentInjector);

  showUrlLater(): string {
    // inject() is only allowed in an injection context, so open one on purpose.
    return runInInjectionContext(this.env, () => inject(Router).url);
  }
}

Angular 20.3, strict template check passes. The `TabComponent` finds its parent group through the element injector. `showUrlLater` is a helper that needs `runInInjectionContext` because it is called outside a constructor.

Key points

  • Two trees: element injectors (components, directives) and environment injectors (route, root, platform).
  • `viewProviders` hide a provider from projected content; `providers` do not.
  • `self`, `skipSelf`, `optional`, and `host` change where the lookup starts and stops.
  • `runInInjectionContext` makes `inject()` work in helper functions.

Common mistakes

  • Calling `inject()` inside an event handler and getting NG0203.
  • Providing a service in both root and a component and unknowingly working with two different instances.
  • Forgetting `optional: true` in a directive that may be used outside its parent, so it throws a NullInjectorError.

Follow-ups

  • What is the difference between `providers` and `viewProviders`?
  • How can a nested tree node get its parent node?
  • How would you override a root provider for one route only?

Tips

  • Explain the lookup order before the options. Everything else follows from it.
  • Use the nested menu or tab-group example for `skipSelf` and `optional`.
  • Mention the NG0203 error as something you have seen.

Evaluation rubric

  • Describes both injector trees and lookup order.
  • Uses inject options correctly.
  • Knows viewProviders and runInInjectionContext.