Sub topic 9
Scoping Services to a Component Subtree
This chapter assumes you know how @Injectable works, how to call inject(), and how a consumer looks up the injector hierarchy to find a provider. Here you will use that lookup on purpose: you register a service on a component, so each instance of that component gets its own copy of the service.
Why scope a service to a component
A service with providedIn: 'root' is a singleton. Every consumer in the app shares one instance. That suits a cart or an auth session. It does not suit state that belongs to one part of the screen, such as a form draft, a single tab group's selection, or the expanded rows of one table. If two editors share one draft service, typing in one editor changes the other.
When you list a service in a component's providers array, Angular creates a new instance in that component's element injector. The component and all of its descendants receive that instance. When the component is destroyed, the instance is destroyed with it.
Providing a service per component
import { Component, Injectable, OnDestroy, inject } from '@angular/core';
@Injectable()
export class FormDraftService implements OnDestroy {
value = '';
ngOnDestroy(): void {
console.log('Draft discarded');
}
}
@Component({
selector: 'app-draft-preview',
standalone: true,
template: `<p>Preview: {{ draft.value }}</p>`
})
export class DraftPreviewComponent {
protected readonly draft = inject(FormDraftService);
}
@Component({
selector: 'app-editor',
standalone: true,
imports: [DraftPreviewComponent],
providers: [FormDraftService],
template: `
<input [value]="draft.value" (input)="draft.value = $any($event.target).value" />
<app-draft-preview />
`
})
export class EditorComponent {
protected readonly draft = inject(FormDraftService);
}
@Component({
selector: 'app-root',
standalone: true,
imports: [EditorComponent],
template: `<app-editor /><app-editor />`
})
export class AppComponent {}Each <app-editor> has its own FormDraftService. The preview inside each editor walks up to the nearest element injector that provides the service, which is its own editor. Typing in one input changes only the preview beside it. Angular calls ngOnDestroy on a component-provided service when the owning component is destroyed, so the service can clean up there.
providers versus viewProviders
A component can render children in two ways. View children are written in its own template. Content children are projected into it through <ng-content> by whoever uses the component. providers makes the service visible to both kinds of children. viewProviders makes it visible only to the component and its view children.
@Component({
selector: 'app-panel',
standalone: true,
imports: [DraftPreviewComponent],
viewProviders: [FormDraftService],
template: `
<app-draft-preview />
<ng-content />
`
})
export class PanelComponent {}Suppose a parent writes <app-panel><app-draft-preview /></app-panel>. The preview inside the panel's template receives the panel's instance. The projected preview does not see it. Its lookup continues through the injectors of the template where it was written. If nothing in that chain provides the service, Angular throws NullInjectorError.
| Option | Component itself | View children | Projected content |
|---|---|---|---|
| `providers` | Yes | Yes | Yes |
| `viewProviders` | Yes | Yes | No |
Use viewProviders when a service is an internal detail of a component and code projected in from outside should not depend on it.
Common errors
- Adding
providedIn: 'root'and also listing the service inproviders. The component's entry wins for its subtree, so that subtree gets a separate instance. People who expect one shared singleton get confused when state seems to "reset." Pick one scope on purpose. - Using
viewProvidersand then injecting from projected content. You get aNullInjectorError, or you silently receive an ancestor's instance. Switch toprovidersif projected content needs the service. - Expecting state to survive navigation. A component-scoped instance is destroyed with its component. Keep state that must survive navigation in a root or route-level service.
Exercise
A TabsComponent lists TabsStateService in viewProviders. A user writes <app-tabs><app-tab /></app-tabs>, and TabComponent calls inject(TabsStateService). No ancestor provides the service. What happens, and what single change fixes it?
Show answer
TabComponent is projected content, so it cannot see TabsComponent's viewProviders. The lookup continues up the injector chain, finds no provider, and Angular throws NullInjectorError. Moving TabsStateService from viewProviders to providers makes the instance visible to projected children.
Exercise
Three <app-editor> elements are rendered and EditorComponent has providers: [FormDraftService]. How many FormDraftService instances exist, and when is each one destroyed?
Show answer
Three instances exist, one per EditorComponent element injector. Each is destroyed, and its ngOnDestroy runs, when its own EditorComponent is destroyed.