liveBook · Manning

InjectionToken

As explained in Modern Angular

InjectionToken is an Angular token used to identify a dependency that is not represented by a class type.

InjectionToken identifies a dependency that is not represented by a class type. It acts as a stable key for associating a value with Angular’s dependency-injection system, allowing configuration and other non-class dependencies to be provided and injected where needed. section 3.1.2

Use an InjectionToken when a dependency is:

  • A primitive or configuration value, such as a character limit. section 3.4.2
  • Provided globally but overrideable for a particular component or directive instance. section 3.4.2
  • Optional, with a fallback value when no provider exists. section 3.4.2

Configurable truncation limit

Define a token with `export const TruncateLimit = new InjectionToken<number>('TruncateLimit')`. Provide `{ provide: TruncateLimit, useValue: 70 }` in application configuration, then inject it into a directive. A local input such as `<td appTruncate [limit]="10">` can override the configured value. For a default, use `inject(TruncateLimit, { optional: true }) ?? 80`. section 3.4.2

Listing 3.18 Injecting a configuration into TruncateDirective
export const TruncateLimit = new InjectionToken<number>('TruncateLimit');  #1

@Directive({
    selector: '[appTruncate]',
    standalone: true,
})
export class TruncateDirective implements AfterViewInit {
    @Input() limit = inject(TruncateLimit);  #2
}

Shows the token declaration and its direct use as an injected directive configuration. section 3.4.2

How Modern Angular covers it

How deep it goes
Explains token registration, injection, provider scope, optional lookup, and fallback behavior without detailing Angular injector internals.
Examples
Demonstrates a TruncateDirective whose character limit supports application-wide configuration, local overrides, and an 80-character default.
What it assumes
Assumes familiarity with Angular dependency injection, providers, directives, inputs, and the inject function.
What you can do after
Apply it via Angular dependency injection to configure reusable directives with globally provided, locally overridden, or default values.
How it connects
Connects InjectionToken to dependency injection, inject, providers, directives, inputs, and lookup modifiers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.