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
