Sub topic 10
providers versus viewProviders
This chapter assumes you know how component-level providers create an element injector entry, and that you can read a standalone component's imports and template. Both options register a service on a component's element injector. They differ in who can see that registration, and the difference matters only when the component projects content with <ng-content>.
Two views of the same component
A component has two kinds of children:
- View children are the elements and components in the component's own template.
- Content children are the elements a parent writes between the component's tags, which the component places with
<ng-content>.
Here is a card that wraps whatever the parent gives it:
<app-card>
<app-card-title /> <!-- content child of app-card -->
</app-card>The <app-card-title /> above is written in the parent's template, so it is a content child of app-card. Its element injector still sits below the app-card host element in the injector tree, so by default it can see everything app-card provides.
providersmakes a provider visible to the component, its view children, and its content children.viewProvidersmakes a provider visible to the component and its view children only. Content children cannot see it.
A runnable comparison
The following code uses an InjectionToken to show which title sees the value.
import { Component, InjectionToken, inject } from '@angular/core';
export const CARD_NAME = new InjectionToken<string>('CARD_NAME');
@Component({
selector: 'app-card-title',
standalone: true,
template: `<h2>{{ name ?? 'no name provided' }}</h2>`,
})
export class CardTitleComponent {
protected readonly name = inject(CARD_NAME, { optional: true });
}
@Component({
selector: 'app-card',
standalone: true,
imports: [CardTitleComponent],
viewProviders: [{ provide: CARD_NAME, useValue: 'Card view' }],
template: `<app-card-title /><ng-content />`,
})
export class CardComponent {}
@Component({
selector: 'app-page',
standalone: true,
imports: [CardComponent, CardTitleComponent],
template: `<app-card><app-card-title /></app-card>`,
})
export class PageComponent {}PageComponent renders two titles:
- The title in
CardComponent's own template printsCard view. It is a view child, so theviewProvidersentry is visible. - The projected title prints
no name provided. It is a content child, so the lookup skips the card'sviewProvidersand continues upward. Nothing above providesCARD_NAME, andoptional: trueturns the miss intonull.
If you change viewProviders to providers in CardComponent, both titles print Card view.
How the lookup treats viewProviders
Angular stores the entries from providers and viewProviders on the same host element injector, but it marks the viewProviders entries as view-only. When a lookup arrives at the host element, Angular checks where the lookup started:
- If it started inside the component's own view (the card's template), the view-only entries count.
- If it started in projected content, which the parent declared, they are skipped and the walk moves on to the parent element injector.
The component class itself can inject its own viewProviders, because they belong to its view. A directive cannot declare viewProviders. Only @Component accepts the option, since only components have a view.
When to use viewProviders
Use viewProviders when a service is an implementation detail of the component and the parent's projected content must not depend on it or collide with it. Typical cases:
- A library component's internal state. A tabs or accordion component keeps a coordination service for its own template. With
viewProviders, a user's projected component cannot inject that service and start depending on library internals. - Isolating a token that the content may provide itself. If projected content can supply its own
CARD_NAME,viewProviderskeeps the card's value out of that content's lookup, so the content falls through to its own or an ancestor's value. - Keeping a public API small. Anything in
providersis effectively part of the component's contract with projected content.viewProvidersis not.
Use plain providers when projected content is meant to use the service. This is the case for the parent-injection pattern from the previous chapter, where a child injects its parent through an abstract token. A Panel token registered in viewProviders would never reach a DialogCloseComponent projected into the dialog.
Comparison
| Aspect | `providers` | `viewProviders` |
|---|---|---|
| Available on | Components and directives | Components only |
| Visible to the host class | Yes | Yes |
| Visible to view children | Yes | Yes |
| Visible to projected content children | Yes | No |
| Typical use | Shared per-instance services, parent tokens | Internal services hidden from projected content |
Interaction with the host modifier
inject(Token, { host: true }) stops the search at the host element of the current component. For a component injecting in its own view, viewProviders on that host are still visible, because the lookup began in the view. This makes host a good fit for a view child that wants the nearest value from its own component but must never pick up one from further up the tree:
import { Component, inject } from '@angular/core';
import { CARD_NAME } from './card-name';
@Component({
selector: 'app-card-heading',
standalone: true,
template: `<h3>{{ name ?? 'standalone heading' }}</h3>`,
})
export class CardHeadingComponent {
protected readonly name = inject(CARD_NAME, { host: true, optional: true });
}If CardHeadingComponent is used in a card's template, it finds the card's viewProviders value. If a parent projects it into a card, the lookup does not see viewProviders, reaches the host boundary, and returns null because of optional: true.
Common mistakes
- Expecting projected content to see
viewProviders. Symptom:NullInjectorError: No provider for Xin a component that you projected into a library component. Fix: move the entry toproviders, or provide the token above the projection site. - Using
viewProviderson a directive. The option does not exist on@Directive, so the compiler rejects it. Useproviders. - Switching to
providersto silence an error. This widens visibility for all projected content. Check first whether the content should be depending on that service at all. - Assuming a projected element's injector chain follows the template where the content appears. It follows where the content is declared. The content is a child of the
app-cardhost element in the declaring template, so lookups from it walk up through that host's injector, and the view-only entries are excluded.
Testing viewProviders
Providers declared on a component are not reachable through TestBed.configureTestingModule({ providers }), and this applies to viewProviders too. Replace them with TestBed.overrideComponent, using set: { viewProviders: [...] } for a component that uses that option. To test the projection boundary, render a small host component that projects a child into your component, and assert on what the child reads. A test that renders only the component's own view cannot show the viewProviders restriction.
Exercise
A TabsComponent declares viewProviders: [TabRegistry] and its template contains <app-tab-bar /> and <ng-content />. A page projects <app-tab-panel /> into the tabs, and TabPanelComponent calls inject(TabRegistry) with no options. What happens for app-tab-bar and for app-tab-panel, and what two changes would let the panel receive the registry?
Show answer
app-tab-bar is a view child, so it receives the TabRegistry instance from the tabs component's viewProviders. app-tab-panel is projected content, so the lookup skips the view-only entry and continues upward. If nothing above provides TabRegistry, it throws NullInjectorError. Two fixes: move TabRegistry from viewProviders to providers on TabsComponent, which makes it visible to the panel and shares the same per-tabs instance, or provide TabRegistry in an injector above the page, though that makes the instance shared more widely.
Exercise
Why can inject(CARD_NAME, { host: true, optional: true }) return null in a heading that is projected into app-card, even though app-card declares viewProviders for CARD_NAME?
Show answer
The projected heading is a content child, so its lookup does not see the host's viewProviders entries. The host option ends the search at the host element boundary, so the lookup does not continue to ancestors above it. No provider is found, and optional: true turns the failure into null.