Sub topic 9
One service instance per component with providers
This chapter assumes you can write a standalone component, you know what inject() does, and you have used a service registered with providedIn: 'root'. It covers how the providers array on a component gives each component instance its own service, and where that scoping stops.
Why scope a service to a component
A root service is a singleton. That suits an API client or an auth session. It does not suit state that belongs to one widget, such as the selected rows of one table, the open step of one wizard, or the draft text of one editor. If that state sits in a root service, two widgets on the same page overwrite each other's data.
You could pass the state down through inputs, or you could give each widget its own service. The second option keeps the widget's logic in one class and lets its child components reach that class without prop drilling. Angular supports it through the providers array of @Component and @Directive.
The providers array
Start with a service that is also registered at the root:
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CounterService {
readonly count = signal(0);
increment(): void {
this.count.update(n => n + 1);
}
}Listing the class in a component's providers creates an entry in that component's element injector. An element injector is the injector Angular attaches to a node in the component tree.
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);
}When inject(CounterService) runs, Angular checks the component's own element injector first. It finds the provider there and stops, so the root registration is never consulted. The root instance still exists if something else asks for it, but this component cannot see it.
Each instance gets its own service
The element injector belongs to a component instance, not to the component class. A template that uses the component twice creates two instances, and each one gets a separate CounterService:
import { Component } from '@angular/core';
import { CounterComponent } from './counter.component';
@Component({
selector: 'app-dashboard',
standalone: true,
imports: [CounterComponent],
template: `<app-counter /><app-counter />`,
})
export class DashboardComponent {}Clicking the first button changes only the first counter. A component rendered inside @for or @if follows the same rule. Each rendered instance gets a fresh service, and a recreated instance starts from the initial state.
Descendants share the nearest provider
The service is not private to the component class. It is visible to everything below the component in the tree. A child that declares no provider of its own receives the nearest ancestor's instance. This is how a component and its helper components share one object.
import { Component, inject } from '@angular/core';
import { CounterService } from './counter.service';
@Component({
selector: 'app-counter-display',
standalone: true,
template: `<span>{{ counter.count() }}</span>`,
})
export class CounterDisplayComponent {
protected readonly counter = inject(CounterService);
}
@Component({
selector: 'app-counter-button',
standalone: true,
template: `<button (click)="counter.increment()">+1</button>`,
})
export class CounterButtonComponent {
protected readonly counter = inject(CounterService);
}
@Component({
selector: 'app-counter-panel',
standalone: true,
imports: [CounterDisplayComponent, CounterButtonComponent],
providers: [CounterService],
template: `<app-counter-display /><app-counter-button />`,
})
export class CounterPanelComponent {}The display and the button have no providers, so both walk up to CounterPanelComponent and share its instance. Click the button and the display updates. Place two <app-counter-panel /> elements on a page and each pair is independent.
The dotted lines show where each child's lookup ends. The root instance is never reached.
Directives work the same way
@Directive accepts providers too. The provider is created once for each element the directive is applied to. This is useful for attribute directives that need per-element state, such as a tooltip directive that tracks its own open or closed flag. Components on the same element see the directive's providers, because the directive and the component share that element's injector.
Lifetime and lazy creation
- Creation is lazy. Angular instantiates a component-level service the first time something asks for it. If nothing injects it, the constructor never runs.
- Destruction follows the component. When Angular destroys the component, it calls
ngOnDestroyon provided instances that define it. This is the right place to close subscriptions or timers that the service opened. - State does not survive. If a route change or an
@ifremoves the component, the service and its state go with it. Move the state higher in the tree if it must outlive the component.
Choosing where to provide
| Place | Instances | Visible to | Typical use |
|---|---|---|---|
| `providedIn: 'root'` | One per application | Everything | API clients, session state |
| Route `providers` | One per route injector | Components under that route | Feature state for a section |
| Component `providers` | One per component instance | That component and its descendants | Widget or form state |
Common errors
State resets or is not shared. You added providers: [SomeService] to a component that should have shared the root instance. The component now has a private copy, and values set elsewhere never appear. Remove the entry from providers if you want the shared instance.
Two components that should share do not. Siblings each listing the service get two instances. Provide it once on their common parent and remove it from both children.
A child gets the wrong instance. A nested component that also lists the service shadows its parent's provider. The nearest provider always wins. Search the chain of ancestors for every providers entry naming the class.
NullInjectorError for a service without providedIn. A class marked only with @Injectable() has no default registration. It works for a component that lists it in providers, but a component outside that subtree has nothing to find and throws NullInjectorError: No provider for .... Either move the provider up to a common ancestor or add providedIn.
Projected content. Content passed through <ng-content /> resolves its dependencies from where it is declared in the template, not from the component that displays it. A service provided on the host is therefore visible to projected content through providers. viewProviders hides it from that content. The two options get their own chapter.
Tests. Component-level providers are not replaced by module-level providers in TestBed. Use TestBed.overrideComponent to swap them, as a later chapter shows.
Exercise
A page contains <app-counter-panel /> twice. The display and the button inside each panel declare no providers. How many CounterService instances exist for these two panels, and which instance does each button update?
Show answer
Two instances, one per panel. Each button and display resolves CounterService from its own panel's element injector, so a button updates only the display inside the same panel. The root instance is not used by either panel.
Exercise
A developer removes providers: [CounterService] from CounterPanelComponent but leaves providedIn: 'root' on the service. The app still compiles and runs. What changes in behavior?
Show answer
All panels now resolve CounterService from the root environment injector, so they share one instance. Clicking any button changes the count shown by every display on the page, and the count is no longer reset when a panel is destroyed.