Sub topic 12
Multi Providers
This chapter assumes you already know how to register providers with useClass, useValue, useFactory, and useExisting, and how to create and inject an InjectionToken. It also assumes you know the difference between environment injectors and element injectors. Those topics are covered in earlier chapters. This one covers a single provider option: multi: true.
The problem multi providers solve
A normal provider maps one token to one value. If you register the same token twice in the same injector, the later registration replaces the earlier one. That works when exactly one implementation should win. Some designs need the reverse: many independent pieces of code each contribute something, and one consumer collects all of the contributions.
Some examples:
- Each feature adds its own command to a command palette.
- Each concern (authentication, logging, retries) adds its own HTTP interceptor.
- Each part of the app runs its own startup task before the app renders.
- Each custom form control registers itself as a validator or value accessor.
You could create a central registry service and ask every feature to call registry.add(...). That couples every feature to the timing of that call and to the registry's API. A multi provider lets each feature declare its contribution as configuration. Angular collects the contributions into an array.
How `multi: true` works
When a provider has multi: true, Angular does not replace the previous value for that token. It appends the new value to a list. Injecting the token returns an array with one entry per multi provider, in the order the providers were registered.
import { InjectionToken } from '@angular/core';
export interface Command {
id: string;
label: string;
run(): void;
}
// The token's type is the array, because that is what inject() returns.
export const COMMANDS = new InjectionToken<readonly Command[]>('COMMANDS');The token is typed as readonly Command[], not Command. inject(COMMANDS) returns whatever type the token declares, and for a multi token that is the collected array. Angular's own HTTP_INTERCEPTORS token follows the same convention: it is declared as InjectionToken<readonly HttpInterceptor[]>. Marking the array readonly stops consumers from pushing into an array that other code also reads.
Each contribution is a separate provider object with multi: true:
import { ApplicationConfig } from '@angular/core';
import { COMMANDS } from './commands';
export const appConfig: ApplicationConfig = {
providers: [
{
provide: COMMANDS,
multi: true,
useValue: { id: 'save', label: 'Save', run: () => console.log('saving') }
},
{
provide: COMMANDS,
multi: true,
useValue: { id: 'open', label: 'Open', run: () => console.log('opening') }
}
]
};The consumer injects the token once and gets both entries:
import { Injectable, inject } from '@angular/core';
import { COMMANDS, Command } from './commands';
@Injectable({ providedIn: 'root' })
export class CommandPalette {
private readonly commands = inject(COMMANDS);
list(): readonly Command[] {
return this.commands;
}
run(id: string): void {
const command = this.commands.find(c => c.id === id);
if (!command) {
throw new Error(`Unknown command: ${id}`);
}
command.run();
}
}Every recipe works with `multi`
multi: true is an option on a provider, so it combines with any recipe. Each entry in the final array is resolved by its own recipe.
import { Injectable, inject } from '@angular/core';
import { COMMANDS, Command } from './commands';
@Injectable()
export class ExportCommand implements Command {
readonly id = 'export';
readonly label = 'Export';
run(): void {
console.log('exporting');
}
}
@Injectable({ providedIn: 'root' })
export class ThemeService {
dark = false;
toggle(): void {
this.dark = !this.dark;
}
}
export const commandProviders = [
// useClass: Angular instantiates ExportCommand for this entry.
{ provide: COMMANDS, multi: true, useClass: ExportCommand },
// useFactory: the factory can call inject() for its own dependencies.
{
provide: COMMANDS,
multi: true,
useFactory: (): Command => {
const theme = inject(ThemeService);
return { id: 'theme', label: 'Toggle theme', run: () => theme.toggle() };
}
}
];useExisting matters when a class must be reachable both directly and as part of the collection. Suppose ExportCommand should also be injectable by its own class, and you want one shared instance:
import { COMMANDS } from './commands';
import { ExportCommand } from './export-command';
export const exportProviders = [
ExportCommand,
{ provide: COMMANDS, multi: true, useExisting: ExportCommand }
];With useClass in the multi entry and a separate ExportCommand provider, you would get two instances: one in the array and one for direct injection. useExisting makes the array entry an alias for the instance that is already registered.
Multi providers in Angular itself
Angular uses multi providers for several of its own extension points. You will see these tokens in older code and libraries even where newer helper functions now wrap them.
| Token | What each entry contributes | Modern alternative |
|---|---|---|
| `HTTP_INTERCEPTORS` | A class-based `HttpInterceptor` | `provideHttpClient(withInterceptors([...]))` with functional interceptors |
| `APP_INITIALIZER` | A function run before the app starts | `provideAppInitializer(fn)` (Angular 19+) |
| `ENVIRONMENT_INITIALIZER` | A function run when an environment injector is created | `provideEnvironmentInitializer(fn)` (Angular 19+) |
| `NG_VALIDATORS` | A validator for a form control directive | Still used directly when writing custom validator directives |
| `NG_VALUE_ACCESSOR` | A `ControlValueAccessor` for a custom form control | Still used directly when writing custom form controls |
The helper functions are thin wrappers that register multi providers for you. For example, provideAppInitializer(fn) returns a provider that adds fn to the initializer collection. Knowing the underlying mechanism helps when you read stack traces or debug ordering.
A custom form control is the most common place you write a multi provider by hand:
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-rating',
standalone: true,
template: `<button type="button" (click)="set(value + 1)">Rating: {{ value }}</button>`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => RatingComponent)
}
]
})
export class RatingComponent implements ControlValueAccessor {
value = 0;
private onChange: (v: number) => void = () => {};
private onTouched: () => void = () => {};
set(v: number): void {
this.value = v;
this.onChange(v);
this.onTouched();
}
writeValue(v: number | null): void {
this.value = v ?? 0;
}
registerOnChange(fn: (v: number) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
}The provider is multi because other directives on the same element, such as DefaultValueAccessor, may also contribute value accessors. The forms package picks the most specific accessor from the array. forwardRef is needed because the class is referenced inside its own decorator, before the class binding exists.
Gotchas and edge cases
Mixing multi and regular providers throws
All providers for a token inside a single injector must agree. If one registration has multi: true and another for the same token in the same injector omits it, Angular throws an error at injector creation stating that it cannot mix multi providers and regular providers. This usually happens when someone copies a provider and forgets the flag.
No contributions means no provider
If no multi provider for the token is registered anywhere, inject(COMMANDS) throws NullInjectorError. It does not return an empty array. When contributions are genuinely optional, ask for the token as optional and default to an empty array:
private readonly commands = inject(COMMANDS, { optional: true }) ?? [];Order follows registration order
Entries appear in the order Angular processes the providers: their position in the providers array, with nested arrays flattened in place. For interceptors and initializers, order changes behavior. An auth interceptor listed after a retry interceptor behaves differently from one listed before it. Don't let correctness depend on import order spread across files. Collect order-sensitive contributions in one place, or give entries an explicit priority field and sort in the consumer.
Child injectors do not merge with parents
This is the most surprising edge case. Each injector builds its own array from its own providers. Resolution stops at the nearest injector that has any provider for the token. If a lazy-loaded route adds a multi provider for COMMANDS in its environment injector, consumers inside that route see only the route's entries, not the root entries plus the route's.
To extend the parent's list, register a single regular provider in the child injector that reads the parent's array with skipSelf and appends to it. This does not count as mixing, because the regular provider and the multi providers live in different injectors.
import { Routes } from '@angular/router';
import { inject } from '@angular/core';
import { COMMANDS, Command } from './commands';
import { ReportsComponent } from './reports.component';
const reportCommand: Command = {
id: 'report',
label: 'Run report',
run: () => console.log('report')
};
export const routes: Routes = [
{
path: 'reports',
component: ReportsComponent,
providers: [
{
provide: COMMANDS,
useFactory: (): readonly Command[] => [
...(inject(COMMANDS, { skipSelf: true, optional: true }) ?? []),
reportCommand
]
}
]
}
];Wrap registration in a helper
A small function removes the risk of a forgotten flag and gives contributors a clean API:
import { Provider } from '@angular/core';
import { COMMANDS, Command } from './commands';
export function provideCommand(command: Command): Provider {
return { provide: COMMANDS, multi: true, useValue: command };
}
// Usage in ApplicationConfig.providers:
// provideCommand({ id: 'save', label: 'Save', run: () => {} })This is the same pattern Angular uses for provideAppInitializer and similar helpers.
When to use a multi provider
Use a multi provider when contributions come from independent places, the consumer treats them uniformly, and the set is fixed when the injector is created. Use a stateful registry service instead when entries must be added or removed at runtime, for example plugins loaded after a user action. An injector's multi array is built once and does not change after that.
Exercise
A root config registers two COMMANDS entries with multi: true. A teammate adds a third registration in the same providers array but forgets multi: true. What happens, and how would you prevent it in the future?
Show answer
Angular throws when it creates the root injector, because multi providers and regular providers for the same token cannot be mixed in one injector. To prevent it, expose a helper such as provideCommand() that always sets multi: true, and have contributors call the helper instead of writing provider objects by hand.
Exercise
The root injector provides COMMANDS entries save and open. A lazy route adds { provide: COMMANDS, multi: true, useValue: reportCommand } to its providers. What does inject(COMMANDS) return in a component inside that route, and how do you make it return all three?
Show answer
It returns only [reportCommand], because the route's environment injector has its own provider for the token and resolution stops there, without merging the parent's array. To get all three, replace the route's multi provider with one regular provider whose useFactory returns [...(inject(COMMANDS, { skipSelf: true, optional: true }) ?? []), reportCommand].
Exercise
You register ExportCommand as a plain provider and also add { provide: COMMANDS, multi: true, useClass: ExportCommand }. A component injects ExportCommand directly and changes a field on it, but the CommandPalette does not see the change. Why, and what is the fix?
Show answer
useClass creates a second, separate instance for the multi entry, so the component and the palette hold different objects. Change the multi entry to useExisting: ExportCommand so the array entry points to the same instance that direct injection returns.