Sub topic 9
Scoping Services to a Component Subtree
A service registered with providedIn: 'root' has one instance for the whole application. That suits caches, HTTP clients, and app-wide state. Some state belongs to a single part of the screen, though. Examples are a form draft, the selection inside one data grid, or the open/closed state of one accordion. If the app shows three editors, each one needs its own draft. This chapter shows how to give a component and its descendants their own private instance of a service, and how to choose between providers and viewProviders.
This chapter assumes you know standalone components, inject(), and @Injectable, and that you have read the previous chapter on environment and element injectors.
The Mechanism: An Element Injector per Component Instance
Angular creates an element injector for each component instance that declares providers (or viewProviders) in its @Component metadata. When the component is created, Angular registers those providers in that injector. When something in the subtree calls inject(SomeService), Angular walks up the element injector chain from the requesting node. The first injector that has a provider for the token creates or returns the instance.
This has three consequences:
- One instance per component instance. Ten
<app-editor>elements mean ten service instances. - Visible downward only. The component and its descendants can see the instance. The parent and siblings cannot.
- Lifetime matches the component. Angular creates the instance when it is first requested, which in practice is while the component is being built. It destroys the instance when the component is destroyed.
Here is the basic form:
import { Component, Injectable, inject } from '@angular/core';
@Injectable()
export class FormDraftService {
value = '';
}
@Component({
selector: 'app-editor',
standalone: true,
providers: [FormDraftService],
template: `<input [value]="draft.value" (input)="draft.value = $any($event.target).value" />`
})
export class EditorComponent {
protected readonly draft = inject(FormDraftService);
private readonly parentDraft = inject(FormDraftService, { skipSelf: true, optional: true });
}FormDraftService uses a bare @Injectable() with no providedIn, which is deliberate. Without providedIn, nobody can inject the service by accident from the root injector. Any consumer outside a component that provides it gets a NullInjectorError, and that error tells you the service was used outside its intended scope.
The parentDraft line is a preview of the resolution modifiers covered later. skipSelf: true starts the lookup at the parent injector. If you nest one editor inside another, the inner editor can reach the outer editor's draft this way. optional: true returns null when no ancestor provides the service.
Lifetime and Cleanup
Component-scoped services can implement ngOnDestroy, and Angular calls it when the owning component is destroyed. This is the right place to stop timers, complete subjects, or cancel subscriptions that the service owns. Root services rarely need this because they live as long as the app.
import { Component, Injectable, OnDestroy, inject, signal } from '@angular/core';
@Injectable()
export class ElapsedTimer implements OnDestroy {
readonly seconds = signal(0);
private readonly handle = setInterval(() => this.seconds.update(s => s + 1), 1000);
ngOnDestroy(): void {
clearInterval(this.handle);
console.log('ElapsedTimer stopped');
}
}
@Component({
selector: 'app-stopwatch',
standalone: true,
providers: [ElapsedTimer],
template: `Elapsed: {{ timer.seconds() }}s`
})
export class StopwatchComponent {
protected readonly timer = inject(ElapsedTimer);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [StopwatchComponent],
template: `
<button (click)="show = !show">Toggle</button>
@if (show) {
<app-stopwatch />
}
`
})
export class AppComponent {
show = true;
}Each time you toggle the stopwatch off, the console logs ElapsedTimer stopped. Each time you toggle it back on, a fresh timer starts at zero. If you moved ElapsedTimer to providedIn: 'root', the interval would never stop and the count would continue across toggles.
You can also call inject(DestroyRef) inside the service and register cleanup with onDestroy(...). In a component-scoped service, that DestroyRef is tied to the component's lifetime.
providers vs viewProviders
Both arrays register providers on the component's element injector. They differ in who can see them, and the difference only shows up with content projection.
providers: visible to the component, its own template (the view), and any content projected into it through<ng-content>.viewProviders: visible to the component and its own template, and hidden from projected content.
Projected content is declared in the parent's template, but its element injector chain still passes through the host element it is projected into. viewProviders exists to put a wall at that point.
import { Component, Injectable, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
@Injectable()
export class PanelTheme {
color = 'blue';
}
@Component({
selector: 'app-theme-label',
standalone: true,
template: `<p>{{ theme?.color ?? 'no theme' }}</p>`
})
export class ThemeLabelComponent {
protected readonly theme = inject(PanelTheme, { optional: true });
}
@Component({
selector: 'app-panel',
standalone: true,
imports: [ThemeLabelComponent],
viewProviders: [PanelTheme],
template: `
<app-theme-label />
<ng-content />
`
})
export class PanelComponent {}
@Component({
selector: 'app-root',
standalone: true,
imports: [PanelComponent, ThemeLabelComponent],
template: `
<app-panel>
<app-theme-label />
</app-panel>
`
})
export class AppComponent {}
bootstrapApplication(AppComponent);The page renders:
blue
no themeThe first label comes from PanelComponent's own template, so it sees the view provider. The second label is projected content written in AppComponent's template, so it cannot see the view provider. If you change viewProviders to providers, both lines read blue.
Use viewProviders when a service is an internal detail of a component that accepts projected content. A design-system card that uses a private layout service is a typical case, because consumers' projected components should not depend on that service. Use providers when projected children are meant to cooperate with the parent. Tabs, accordions, and form groups are typical cases: a <app-tab> projected into <app-tabs> needs to inject the tabs controller.
| Registration | Instances | Visible to own view | Visible to projected content | Destroyed with |
|---|---|---|---|---|
| `providedIn: 'root'` | One per app | Yes | Yes | Application |
| Component `providers` | One per component instance | Yes | Yes | Component |
| Component `viewProviders` | One per component instance | Yes | No | Component |
| Directive `providers` | One per directive instance | Host element and below | Yes | Directive |
Directives Can Provide Too
@Directive also accepts providers. Because a component and its directives share one element injector, a directive on the same element can provide a service that the component injects, and the reverse also works. This is useful for attaching behavior with an attribute, such as an appSelectionScope directive that provides a SelectionService to everything under the element it sits on. Directives do not have viewProviders, because they have no view of their own.
Common Errors
Shadowing a root service by accident
If a service has providedIn: 'root' and you also list it in a component's providers, you get two instances. The component and its subtree see the local one, and everything else sees the root one. State written in one place never shows up in the other. This mistake often comes from copying a providers array between components. Remove the local entry unless you want an isolated copy.
Expecting a parent to see a child's service
Resolution only walks up the tree. A parent component that injects a service provided by its child gets the root instance or a NullInjectorError, never the child's instance. If the parent needs it, move the provider up to the parent.
Using viewProviders where projection needs the service
A tabs component that registers its controller in viewProviders breaks every projected <app-tab>. The error is NullInjectorError: No provider for TabsController, or a silent null when the tab injects with optional. Switch to providers.
Assuming a lazy route provider is component-scoped
Route-level providers create an environment injector for the route subtree. That injector lives as long as the route configuration stays loaded, which is usually the rest of the session. It is not destroyed when you navigate away. When you need per-visit state, provide the service on the routed component instead.
Exercise
A ConfirmDialogComponent lists DialogState in providers. Inside its template it renders <app-dialog-footer>, and the parent page projects an <app-help-link> into it through ng-content. Both child components inject DialogState. Which of them receive the dialog's instance, and what changes if DialogState moves to viewProviders?
Show answer
With providers, both children receive the dialog's DialogState, because the footer is in the dialog's view and the projected help link's injector chain passes through the dialog's host element. With viewProviders, only app-dialog-footer receives it. app-help-link continues up past the dialog and gets an ancestor's instance or a root instance if one exists. Otherwise it gets a NullInjectorError, or null if it injected with optional: true.
Exercise
A CounterService has @Injectable({ providedIn: 'root' }). CounterPanelComponent also lists CounterService in providers. A header component outside the panel and a button inside the panel both increment the counter. Why does the header's display not change when the button is clicked, and how do you fix it?
Show answer
The panel's providers entry creates a second instance that shadows the root one for the panel's subtree. The button increments the panel's instance and the header reads the root instance. Remove CounterService from the panel's providers so both resolve to the single root instance.
Exercise
You need a per-editor undo history that is discarded when the editor closes and that releases a subscription to a keyboard-shortcut stream. Where do you provide the service, and where do you put the cleanup?
Show answer
Give the service a bare @Injectable() and list it in the EditorComponent's providers, so each editor gets its own history and the history is destroyed with that editor. Put the cleanup in the service's ngOnDestroy (or register it with inject(DestroyRef).onDestroy), which Angular calls when the owning editor is destroyed.