Sub topic 4
Two hierarchies: environment injectors and element injectors
This chapter assumes you can write standalone components, have registered a service with @Injectable before, and have seen a Routes array. It does not cover how a single lookup is resolved step by step. That comes in a later chapter. Here the goal is a clear model of the two injector trees that lookup walks through.
Why Angular has more than one injector
A beginner's picture of dependency injection (DI) has one container that holds every service. Angular has many injectors, arranged in two trees. Which tree a provider lives in decides who can see it, how long it lives, and whether two classes share one instance or get separate ones.
The two trees are:
- Environment injectors. They are not tied to the DOM. They hold providers for the platform, the application, and for routes.
- Element injectors. There is one conceptually for each element in the template that hosts a component or directive. They follow the component tree.
The environment injector hierarchy
An environment injector is created for things that exist outside any single template. The chain, from the top down, looks like this:
- Platform injector. One per page. It holds a few low-level providers shared by every Angular application on the page.
- Root environment injector. One per application. It is created by
bootstrapApplication. It holds theprovidersyou pass to that function and every service markedprovidedIn: 'root'. - Route environment injectors. Created for routes that declare a
providersarray. Each one has the nearest parent route injector, or the root, as its parent.
Providers in this tree are created lazily. An instance is built the first time something asks for it, and then the same instance is returned from that injector for as long as the injector lives. The root injector lives as long as the application. A route injector lives as long as the router keeps that route's configuration loaded, which in practice means it is not destroyed when you navigate away from the route.
Registering at root
The simplest registration is providedIn: 'root'. The service is tree-shakable: if nothing injects it, it is left out of the bundle.
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly count = signal(0);
increment(): void {
this.count.update(n => n + 1);
}
}The whole application shares one CounterService, because the root environment injector builds it once.
Registering on a route
A route can carry its own providers. Angular creates an environment injector for that route and puts the providers in it.
import { Routes } from '@angular/router';
import { AdminComponent } from './admin.component';
import { AdminSettingsService } from './admin-settings.service';
export const routes: Routes = [
{
path: 'admin',
component: AdminComponent,
providers: [AdminSettingsService],
},
];Components rendered under the admin route can inject AdminSettingsService. Code outside that route cannot reach it, because lookups only travel upward, never sideways or down.
Overriding a token at bootstrap
Tokens that have a default factory can be overridden for the root injector by passing providers to bootstrapApplication.
import { InjectionToken } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
export const API_URL = new InjectionToken<string>('API_URL', {
providedIn: 'root',
factory: () => '/api',
});
bootstrapApplication(AppComponent, {
providers: [{ provide: API_URL, useValue: 'https://example.com/api' }],
});Without the bootstrap provider, inject(API_URL) returns '/api'. With it, the root injector holds an explicit provider and that wins over the default factory.
The element injector hierarchy
Element injectors work differently. You never create one yourself. Angular gives every element that hosts a component or directive a place in the element injector tree, and that tree has the same shape as your rendered DOM of components.
A provider reaches an element injector when you list it in a component's or directive's providers array (or viewProviders, covered in a later chapter).
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter',
standalone: true,
providers: [CounterService],
template: `<button (click)="counter.increment()">{{ counter.count() }}</button>`,
})
export class CounterComponent {
protected readonly counter = inject(CounterService);
}Each time Angular creates an app-counter element, that element's injector gets its own CounterService. Two counters on a page show two independent numbers. The same service class, registered with providedIn: 'root', would still exist in the root injector, but the component's own entry is found first and hides it.
The instance lives as long as the element. When the component is destroyed, its injector goes with it, and so does the service instance (including any ngOnDestroy hook on the service, which Angular calls).
How the two trees connect
The trees are separate, but a lookup passes from one to the other. The rule is:
- Start at the element injector of the component or directive asking.
- Walk up through its parent element injectors.
- If no element injector has the token, switch to the environment injector tree. Start at the closest environment injector for that part of the app (a route injector if the component was rendered through a route with providers, otherwise root).
- Walk up through environment injectors to the platform injector.
- If nothing provides the token, throw
NullInjectorError, unless the request was markedoptional.
So element injectors are always checked first, and environment injectors are the fallback. That ordering is why a component-level provider can hide a root one, and why the opposite never happens.
The later chapter on the resolution algorithm covers the details and the modifiers that alter this walk. For now, hold on to the two facts: the walk goes up only, and element injectors come before environment injectors.
Choosing where a provider belongs
The decision comes from how many instances you want and how long they should live.
| Registration | Tree | Instances | Lifetime |
|---|---|---|---|
| `providedIn: 'root'` | Environment (root) | One per application | The application |
| `bootstrapApplication` providers | Environment (root) | One per application | The application |
| Route `providers` | Environment (route) | One per route injector | While the route configuration is loaded |
| Component or directive `providers` | Element | One per element | While the element exists |
A practical rule: start with providedIn: 'root'. Move a provider to a route when a feature area needs its own state and nothing else should see it. Move it to a component when each instance of that component needs private state.
Common mistakes at this level
- Expecting a route service to be recreated on every navigation. A route injector is created once for the route configuration, so its services keep their state when you leave and return.
- Listing a root service in a component's
providersby accident. This silently creates a second copy. Components that inject the service from the component see different data from the rest of the app. - Expecting a parent to see a child's provider. Lookups never go down. A parent that needs a child's service must be handed it another way, such as an output, or a query on the child.
- Forgetting that a component's providers are reachable by its children. Descendants in the element tree can inject a parent component's provider, which is useful, but it also means a deep child can pick up a service you did not intend it to use.
Exercise
An application has CounterService registered with providedIn: 'root'. A page shows two CounterComponent elements, and CounterComponent lists CounterService in its own providers. A third component, StatusBarComponent, has no providers and injects CounterService. How many CounterService instances exist, and which one does StatusBarComponent receive?
Show answer
Three instances exist: one in each of the two CounterComponent element injectors, and one in the root environment injector. StatusBarComponent receives the root instance, because its element injector chain contains no CounterService and the lookup falls through to the root environment injector. Neither counter's private instance is visible to it, since lookups only travel upward.
Exercise
You want admin pages to share one AdminSettingsService that no other part of the application can inject. Which registration fits, and in which tree does the instance live?
Show answer
Put AdminSettingsService in the providers array of the admin route. Angular creates a route environment injector for that route, so the instance lives in the environment tree, shared by components rendered under the route and invisible elsewhere.