Sub topic 8
Element injectors follow the component tree
This chapter assumes you know TypeScript decorators, standalone components, and how to write a basic injectable service. The previous chapter split Angular's injectors into two hierarchies. This one covers the second: element injectors, which follow the structure of your templates.
What an element injector is
Every element in a template that hosts a component or directive has a place in the element injector tree. The tree mirrors the nesting of elements in your templates. Each element's parent in the tree is the nearest enclosing element that hosts a component or directive.
An element injector is not a separate object created for every node. Angular stores providers in the node's view data and links each node to its parent node. Walking from a child to its ancestors is a walk through those links. If no element on the path has a matching provider, the lookup continues in the environment injectors you saw earlier. A component with no providers costs almost nothing.
The tree follows templates, not class inheritance. A component that extends another class does not gain access to the base class's injector. Only the position of the element in a template matters.
Declaring providers on a component
When you list a service in a component's providers, Angular registers it in that component's element injector. Any component or directive in that component's template can then receive that instance. This includes deeply nested ones.
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter-button',
standalone: true,
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterButtonComponent {
protected readonly counter = inject(CounterService);
}
@Component({
selector: 'app-counter-group',
standalone: true,
imports: [CounterButtonComponent],
providers: [CounterService],
template: `
<app-counter-button />
<app-counter-button />
`,
})
export class CounterGroupComponent {}
@Component({
selector: 'app-root',
standalone: true,
imports: [CounterGroupComponent],
template: `
<app-counter-group />
<app-counter-group />
`,
})
export class AppComponent {}This template creates four buttons. The two buttons inside the first group share one CounterService, and the two inside the second group share a different one. CounterButtonComponent declares no providers, so each button asks its ancestors. The nearest ancestor with a CounterService provider is the enclosing app-counter-group.
If you removed providers: [CounterService] from CounterGroupComponent, all four buttons would share the providedIn: 'root' instance from the previous chapter's service.
The dotted line marks the hand-off. Element injectors form one chain, and when that chain finds nothing, the lookup moves to the environment injector.
Several directives on one element
A single element can host one component and several directives. They all share the same element injector. A provider declared by any of them is visible to the others on that element.
import { Directive, HostListener, Injectable, inject } from '@angular/core';
@Injectable()
export class ClickLog {
readonly entries: string[] = [];
}
@Directive({
selector: '[appClickLog]',
standalone: true,
providers: [ClickLog],
})
export class ClickLogDirective {
private readonly log = inject(ClickLog);
@HostListener('click')
onClick(): void {
this.log.entries.push(new Date().toISOString());
}
}Note that ClickLog has a bare @Injectable() with no providedIn. It has no root registration, so it is available only where something lists it in providers. Consider a template that writes <app-report appClickLog />. ReportComponent is on the same element as the directive, so it can call inject(ClickLog) and get the instance the directive provides. Elements outside that element's subtree cannot see it, and injecting it there throws NullInjectorError.
Where providers can be declared
The list below shows which injector each declaration site populates.
| Declaration site | Injector that receives the provider | Who can see it |
|---|---|---|
| `@Component({ providers })` | Element injector of the host element | The component, its template, and projected content |
| `@Directive({ providers })` | Element injector of the host element | The element, its other directives, and descendants |
| `@Component({ viewProviders })` | Element injector of the host element | The component's own template only (next chapter) |
| `@Injectable({ providedIn: 'root' })` | Root environment injector | Everything |
| Route `providers` | Environment injector created for the route | Components rendered under that route |
Embedded views and control flow
Blocks such as @if and @for, and structural directives such as *ngIf, create embedded views. These views do not add a layer to the element injector tree. An element inside an @for block resolves dependencies through the same ancestors it would have outside the block.
The consequence is that a provider on the element hosting a @for block is shared by every repeated row. Rows do not get their own instance. To get one service instance per row, put the provider on a component that you render once per row, as in this example.
import { Component, Input } from '@angular/core';
import { RowStateService } from './row-state.service';
@Component({
selector: 'app-row',
standalone: true,
providers: [RowStateService],
template: `<span>{{ label }}</span>`,
})
export class RowComponent {
@Input({ required: true }) label = '';
}Then @for (item of items; track item.id) { <app-row [label]="item.name" /> } creates one RowStateService per app-row. Angular creates the instance lazily, the first time something on that element injects it.
Projected content uses the declaring template
With content projection, the tree follows where the markup is written, not where Angular renders it. Take this template.
import { Component } from '@angular/core';
import { CardComponent } from './card.component';
import { BadgeComponent } from './badge.component';
@Component({
selector: 'app-page',
standalone: true,
imports: [CardComponent, BadgeComponent],
template: `
<app-card>
<app-badge />
</app-card>
`,
})
export class PageComponent {}app-badge is written as a child of app-card. Its element injector parent is therefore app-card, even though the card's template decides where the badge appears in the DOM. If CardComponent lists a service in providers, the badge can inject it. This is the main reason providers and viewProviders behave differently, and the next chapter covers that difference.
Components created in code follow a similar rule. When you call ViewContainerRef.createComponent, the new component's element injector parent is the element where the view container sits. You can pass an injector option to change that.
Choosing element-level scope
Use component providers when state belongs to one component instance or one subtree. Typical cases are form state, a table's selection model, or a wizard's step state. Each instance of the component gets fresh state, and Angular destroys the service when the component is destroyed. A service with an ngOnDestroy method gets that hook called at that moment.
Avoid component providers for anything that should be a singleton. A service that holds a user session and is listed in several components' providers produces several sessions, and no error is raised. This is a common cause of "my service has no data" bugs, and the pitfalls chapter returns to it.
Key points
- Element injectors form a tree that follows template nesting, with one place in the tree per element hosting a component or directive.
- Providers on a component or directive are visible to that element, its other directives, and its descendants.
- Control-flow blocks add no injector layer. A provider on the surrounding element is shared by all rows.
- Projected content resolves through the template where it is written.
- When the element chain finds nothing, resolution continues in the environment injectors.
Exercise
A ListComponent has providers: [SelectionService] and its template contains @for (item of items; track item.id) { <app-item [item]="item" /> }. ItemComponent injects SelectionService and declares no providers. How many SelectionService instances exist for a list of five items, and what change would give each item its own?
Show answer
One instance exists, created for the ListComponent element and shared by all five ItemComponent instances. The @for block does not add an injector layer, so each item resolves up to ListComponent. To give each item its own instance, add providers: [SelectionService] to ItemComponent. Each item then finds the provider on its own element first.
Exercise
In <app-card><app-badge /></app-card> written inside PageComponent's template, CardComponent lists ThemeService in providers. Can BadgeComponent inject ThemeService from the card? Explain which injector parent it uses.
Show answer
Yes. The element injector tree follows where the markup is declared. app-badge is written as a child of app-card, so its parent in the tree is the card's element injector, where ThemeService is registered. The DOM position chosen by the card's template does not matter.