Content Queries and Content Projection
What content queries are for
Section titled “What content queries are for”A content query finds elements a consumer passed into your component — the children nested inside your component’s tag at the usage site — as opposed to a view query, which finds elements in your own template.
<!-- The consumer's template --><custom-expando> <custom-toggle>Show</custom-toggle> <!-- content: contentChild finds this --></custom-expando><!-- custom-expando's own template --><div class="panel"> <ng-content /> <!-- where the content is rendered --> <panel-footer /> <!-- view: viewChild finds this --></div>The distinction matters because it determines who owns the element — and ownership determines change detection and dependency injection, which is where the surprising behaviour comes from.
Content projection
Section titled “Content projection”<ng-content> marks where projected content is rendered. A select attribute routes different content to different slots:
<div class="card-shadow"> <ng-content select="card-title" /> <div class="card-divider"></div> <ng-content /> <!-- everything not matched above --></div>A bare <ng-content> is the catch-all. Put it last, or it swallows content the later selectors were meant to receive.
Fallback content goes inside the element and renders when nothing matches:
<ng-content select="card-title">Untitled</ng-content>ngProjectAs lets a consumer route an element that does not match a selector on its own:
<custom-card> <h3 ngProjectAs="card-title">Hello</h3> <p>Body text</p></custom-card>Angular compares the ngProjectAs value against the selectors instead of the element’s own identity. It accepts static values only — it cannot be bound to an expression.
One structural rule worth knowing: <ng-content> does not create the element it projects into — the projected nodes are moved into place, so the consumer’s markup, not yours, determines the tags in the final DOM.
Content queries
Section titled “Content queries”@Component({ selector: 'custom-menu', /* ... */ })export class CustomMenu { readonly items = contentChildren(CustomMenuItem); readonly labels = computed(() => this.items().map((i) => i.label));}contentChild returns a signal of one result (or undefined); contentChildren returns a signal of an array. All query functions return signals that stay up to date, so they work directly in computed and effect.
Required queries
Section titled “Required queries”An unfound contentChild is undefined, and the type reflects that — which is correct, because an @if can remove the target at any point. When a child genuinely must be present, contentChild.required reports an error if it is missing and removes undefined from the type:
readonly body = contentChild.required(CustomCardBody);The descendants asymmetry
Section titled “The descendants asymmetry”This one catches everyone:
contentChildtraverses into descendants by default.contentChildrenfinds only direct children by default.
<custom-expando> <some-wrapper> <custom-toggle>Show</custom-toggle> </some-wrapper></custom-expando>Here contentChild(CustomToggle) finds the toggle and contentChildren(CustomToggle) finds nothing. Set { descendants: true } on contentChildren when consumers may wrap content.
View queries have no descendants option — they always traverse descendants.
Queries never pierce component boundaries
Section titled “Queries never pierce component boundaries”A query only sees elements declared in the same template as the query’s own component. It cannot reach into a child component’s template. That is a hard boundary, and it is the correct one: a component’s internal structure is not its parent’s business.
Locators and options
Section titled “Locators and options”The first argument is the locator:
readonly toggle = contentChild(CustomToggle); // component or directivereadonly saveBtn = viewChild<ElementRef>('save'); // template reference variablereadonly special = contentChild(SUB_ITEM); // any ProviderTokenWhen several elements share a template reference variable, the query returns the first match. CSS selectors are not supported as locators.
Any ProviderToken works, which enables a nice pattern: a child declares a marker token in its providers, and the parent queries for that token instead of a concrete class — decoupling the parent from the child’s implementation.
The read option retrieves something other than the located thing from the matched element’s injector:
readonly template = contentChild(ExpandoContent, { read: TemplateRef });readonly host = viewChild('panel', { read: ElementRef });ElementRef and TemplateRef are the overwhelmingly common cases.
Two caveats that cause real bugs
Section titled “Two caveats that cause real bugs”Projected content belongs to the parent’s view
Section titled “Projected content belongs to the parent’s view”Projected content is rendered inside the receiving component but is still owned by the component that declared it, and Angular tracks it as part of the parent’s view. Two consequences:
Change detection. Projected content is checked when the parent runs change detection. If the receiving component is OnPush, Angular can skip that component’s own template — but not the projected content, because that is the parent’s:
<!-- Parent with eager change detection --><onpush-wrapper> <!-- Still checked on every parent cycle. OnPush on the wrapper does not help. --> <expensive-component /></onpush-wrapper>Wrapping something expensive in an OnPush component does not make it cheap. The optimisation has to happen where the content is declared.
Dependency injection. Projected content resolves dependencies from the parent’s injector, not from the receiving component’s viewProviders. This is exactly the distinction viewProviders exists to express: providers on a component are visible to projected content, viewProviders are not. For a reusable component, put internal collaborators in viewProviders so a consumer’s projected content cannot accidentally resolve against your internals.
Some library components do not support projected children
Section titled “Some library components do not support projected children”Menus, tabs and lists commonly use contentChildren to find their children and wire up keyboard navigation, focus management and ARIA attributes. They are written assuming they own those children directly.
Wrapping such children in an extra layer and projecting them in tends to break subtly: the query still finds the items, but the internal setup that makes them interactive may not work correctly when the items come from a different view context. Keyboard navigation and screen-reader support are the usual casualties, and they fail silently — the component looks right and is unusable without a mouse.
Check a library component’s documentation before projecting into it.
The decorator API
Section titled “The decorator API”@ContentChild, @ContentChildren, @ViewChild and @ViewChildren remain fully supported, but the signal functions are recommended for new code. The differences that matter:
- Timing. Decorator view-query results become available in
ngAfterViewInitand areundefinedbefore that. Content-query results become available inngAfterContentInit. Signal queries are just signals — read them whenever, in any reactive context, and get the current value. - Multiple results.
@ViewChildrenproduces aQueryListwith achangesobservable.viewChildrenproduces a signal of an array, which composes withcomputeddirectly and needs no subscription. - Requiredness.
viewChild.required/contentChild.requiredenforce presence and narrow the type; decorators have no equivalent.
The lifecycle-timing difference is the main practical win. A great deal of ngAfterViewInit code exists solely because a decorator query was not readable earlier — with signal queries, a computed replaces it.
ng generate @angular/core:signal-queries-migrationA worked example
Section titled “A worked example”An accordion that manages its own panels:
@Component({ selector: 'accordion-panel', /* ... */ })export class AccordionPanel { readonly title = input.required<string>(); readonly expanded = model(false);}
@Component({ selector: 'accordion-group', template: `<ng-content />`,})export class AccordionGroup { readonly multiple = input(false, { transform: booleanAttribute }); readonly panels = contentChildren(AccordionPanel, { descendants: true });
readonly expandedCount = computed( () => this.panels().filter((p) => p.expanded()).length, );
constructor() { effect(() => { if (this.multiple()) return; const open = this.panels().filter((p) => p.expanded()); // Single-select: collapse all but the most recently opened. open.slice(0, -1).forEach((p) => p.expanded.set(false)); }); }}Three things this demonstrates: descendants: true so consumers may wrap panels in layout markup; computed over a query signal, with no AfterContentInit and no QueryList.changes subscription; and an effect used for the one thing effects are for — pushing state into something that is not itself a derivation.
Common mistakes
Section titled “Common mistakes”| Mistake | Consequence | Fix |
|---|---|---|
Bare <ng-content> before selective ones |
It absorbs everything | Put the catch-all last |
contentChildren without descendants: true |
Finds nothing when consumers wrap content | Set the option |
| Expecting a query to reach into a child component | Always undefined |
Queries never pierce component boundaries |
Expecting OnPush to skip projected content |
It is checked with the parent | Optimise where the content is declared |
Internal service in providers, not viewProviders |
Projected content resolves against your internals | Use viewProviders for internals |
| Projecting into a library menu or tab list | Keyboard and ARIA support break silently | Check the component’s docs first |
| CSS selector as a locator | Not supported | Use a component, directive, token, or template variable |
Reading a decorator query before ngAfterContentInit |
undefined |
Use signal queries, or wait for the hook |
| Non-required query for a mandatory child | undefined handling everywhere |
contentChild.required |
ngProjectAs bound to an expression |
Static only | Use a literal |
Related pages
Section titled “Related pages”- Input Properties
- Host Binding and Host Listening
- Dependency Injection in Angular
- Change Detection and Zoneless Angular
- Component basics