Sub topic 9
Reading projected content with content queries
Content projection moves markup from a parent into a child's template. Sometimes the child also needs to look at what it received: count the tabs, read their titles, or check whether the parent supplied an actions area at all. Content queries do this. This chapter assumes you know ng-content with select, signal inputs, and computed. It also assumes you know that the parent creates projected content (the previous chapters on ownership and eager creation).
What a content query is
A content query asks Angular for nodes that the parent declared between the host's tags. Angular has two signal-based query functions for this:
| Function | Returns | When nothing matches | Column |
|---|---|---|---|
| `contentChild(locator)` | `Signal<T \ | undefined>` | `undefined` |
| `contentChild.required(locator)` | `Signal<T>` | Reading throws an error (NG0951) | |
| `contentChildren(locator)` | `Signal<ReadonlyArray<T>>` | An empty array |
The locator is one of these:
- A component or directive class, such as
TabComponent. - A template reference variable name as a string, such as
'actions'. - A
TemplateReftype, as in the lazy-box example at the end of this chapter.
Use content queries only in a component or directive class. They return a signal, so you read them by calling them: this.tabs().
A content query is different from a view query (viewChild, viewChildren). A view query searches the component's own template. A content query searches the markup the parent wrote between the component's tags. The same distinction applies to ng-content: content belongs to the parent's template, not to yours.
A first example: tabs that know their children
The app-tabs component should build its navigation from whatever app-tab children the parent supplies. It should not need a separate list of titles.
import { Component, TemplateRef, computed, contentChildren, input, signal, viewChild } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
@Component({
selector: 'app-tab',
template: `
<ng-template>
<ng-content />
</ng-template>
`,
})
export class TabComponent {
title = input.required<string>();
body = viewChild.required(TemplateRef);
}
@Component({
selector: 'app-tabs',
imports: [NgTemplateOutlet],
template: `
<nav>
@for (tab of tabs(); track tab; let i = $index) {
<button
[class.active]="i === selectedIndex()"
(click)="selectedIndex.set(i)"
>
{{ tab.title() }}
</button>
}
</nav>
@if (current(); as tab) {
<ng-container [ngTemplateOutlet]="tab.body()" />
}
`,
})
export class TabsComponent {
tabs = contentChildren(TabComponent);
selectedIndex = signal(0);
current = computed(() => this.tabs()[this.selectedIndex()]);
}The parent uses it like this:
<app-tabs>
<app-tab title="Profile"><p>Profile form</p></app-tab>
<app-tab title="Billing"><p>Billing details</p></app-tab>
</app-tabs>Three things happen here.
- The parent's template creates both
TabComponentinstances. This is the same eager creation you saw earlier. contentChildren(TabComponent)collects those instances.TabsComponentthen reads each instance'stitle()signal and itsbody()template.- Each tab wraps its
ng-contentin anng-template, so the tab's projected content is rendered only whereTabsComponentplaces the template.TabsComponenthas nong-contentof its own. The tab elements are never attached to the DOM, and only the selected tab's body is.
Timing: when results are available
Query results are filled in after Angular has created the parent's content. That has two consequences.
- In the constructor or a field initializer, the signal exists but holds no results yet. Reading it there gives
undefinedforcontentChildand[]forcontentChildren. - Because the result is a signal, you rarely need to care. Read it inside a template, a
computed, or aneffect. Each of those re-runs when the results become available or change.
This is the reason current above is a computed. When the parent adds or removes a tab with @if or @for, tabs() updates. current and the template update with it, and you write no lifecycle code.
The decorator versions, @ContentChild and @ContentChildren, give you the results in ngAfterContentInit. In new code, prefer the signal functions. They remove the need to choose a lifecycle hook.
The `descendants` option
The two functions differ in how deep they look by default.
contentChildrendefaults todescendants: false. It matches only elements that are direct children of the host in the parent's template.contentChilddefaults todescendants: true. It matches nested elements as well.
That default surprises people. If the parent wraps tabs in another element, the default contentChildren finds nothing:
<app-tabs>
<div class="wrapper">
<app-tab title="Profile">...</app-tab>
</div>
</app-tabs>Here tabs() is empty, because the div sits between app-tabs and app-tab. To match nested tabs, opt in:
tabs = contentChildren(TabComponent, { descendants: true });Choose deliberately. descendants: false keeps a nested app-tabs from collecting the tabs of an inner app-tabs. If tab sets can be nested, leave the default alone.
Querying by template reference variable
A string locator matches a template reference variable that the parent declared in the content. This is useful when the child only needs to know whether something exists:
import { Component, computed, contentChild } from '@angular/core';
@Component({
selector: 'app-card',
template: `
<div class="card">
<ng-content />
</div>
@if (hasActions()) {
<footer class="card-footer">
<ng-content select="[card-actions]" />
</footer>
}
`,
})
export class CardComponent {
actions = contentChild('actions');
hasActions = computed(() => this.actions() !== undefined);
}<app-card>
<p>Body</p>
<button #actions card-actions>Save</button>
</app-card>The #actions variable marks the node. contentChild('actions') finds it, and the footer wrapper appears only when the parent supplied the node. The card must not use @if around its slot unless you accept the cost that the next section explains.
Without the query, the footer <footer> and its styling would always render, leaving an empty padded bar. Fallback content cannot solve this. It only fills the inside of a slot. It cannot remove the wrapper around it.
The `read` option
By default a component locator returns the component instance. A string locator returns an ElementRef for a plain element or the component instance for a component. The read option picks something else from the same node:
import { ElementRef, contentChild } from '@angular/core';
export class CardComponent {
// The DOM element of the node marked #actions, not a component instance.
actionsEl = contentChild('actions', { read: ElementRef });
}Common values for read are ElementRef, ViewContainerRef, TemplateRef, and a directive or component class. If the node does not have what you ask for, the query fails to match.
Queries do not depend on slots
A content query finds nodes because of where the parent declared them. It does not care whether they were projected anywhere.
Take this child:
@Component({
selector: 'app-hidden-tabs',
template: `<p>Tabs found: {{ tabs().length }}</p>`,
})
export class HiddenTabsComponent {
tabs = contentChildren(TabComponent);
}<app-hidden-tabs>
<app-tab title="A">...</app-tab>
<app-tab title="B">...</app-tab>
</app-hidden-tabs>The text shows "Tabs found: 2" although the child has no ng-content. The parent created both tab instances, and the query sees them. This matches the eager-creation rule from the previous chapter. Nothing is rendered, yet the components exist and run their constructors and bindings.
The reverse also holds. A node inside an ng-template that no one renders is not created. A content query for that node returns nothing until the template is instantiated.
Choosing a content query or a different tool
Content queries are one of several ways to let a child talk about its projected content.
| Need | Tool |
|---|---|
| Know how many children, or read their inputs | `contentChildren` |
| Know whether an optional piece exists | `contentChild` |
| Place a piece in a specific spot | `ng-content select` |
| Render a piece only when needed | `ng-template` with `ngTemplateOutlet` |
| Let children call methods on a parent | Dependency injection, with the parent as the provider |
A query reads from the parent's content downward. If a child needs something from the host, inject the host in the child. Do not use queries for that direction.
Lazy content with a template query
The lazy-box component from the spine uses a content query that returns a TemplateRef:
import { Component, TemplateRef, contentChild, input } from '@angular/core';
import { NgTemplateOutlet } from '@angular/common';
@Component({
selector: 'app-lazy-box',
imports: [NgTemplateOutlet],
template: `
@if (open()) {
<ng-container [ngTemplateOutlet]="body()" />
}
`,
})
export class LazyBoxComponent {
open = input(false);
body = contentChild.required(TemplateRef);
}<app-lazy-box [open]="isOpen">
<ng-template><app-heavy-widget /></ng-template>
</app-lazy-box>The parent declares the template, but Angular creates app-heavy-widget only when open() becomes true. The query hands the child the TemplateRef, which is a recipe and not an instance. Compare this with ng-content, which would have created the widget as soon as the parent rendered.
contentChild.required is appropriate here because the component cannot work without a template. If the parent forgets it, reading body() throws. For optional content, use plain contentChild and handle undefined.
Common errors
- Empty
contentChildrenresult. Check for a wrapper element between host and child, and adddescendants: trueif you want nested matches. Also check that you queried the class actually used in the parent's template. - Mixing up view and content queries. If the target is in the component's own template, use
viewChild. If the parent wrote it between your tags, usecontentChild. - Reading a query too early. Do not read it in a constructor. Read it in
computed,effect, or the template. - Wrong
readtoken. If the query returnsundefinedafter you addedread, the node cannot supply that token. Removereadto confirm the match exists. - Relying on a query to avoid rendering a slot. The parent still creates the content. Use
ng-templatewhen you want the creation itself to wait. - Using
.requiredfor optional content. The component then throws when the parent leaves that content out.
Exercise
A parent writes <app-tabs><section><app-tab title="A"></app-tab></section></app-tabs>. TabsComponent uses tabs = contentChildren(TabComponent), and tabs().length is 0. Why, and how do you fix it?
Show answer
contentChildren defaults to descendants: false, so it matches only direct children of the host. The section element sits between app-tabs and app-tab, so the tab is not a direct child. Fix it with contentChildren(TabComponent, { descendants: true }), or remove the wrapper from the parent's template.
Exercise
CardComponent has <ng-content select="[card-actions]" /> inside a <footer>. Fallback content cannot hide the footer when the parent supplies no actions. Which content query lets the card render the footer only when actions exist, and what must the parent do?
Show answer
Use actions = contentChild('actions') with hasActions = computed(() => this.actions() !== undefined), and wrap the footer in @if (hasActions()). The parent marks the action node with a template reference variable, such as <button #actions card-actions>Save</button>.
Exercise
HiddenTabsComponent has no ng-content, yet contentChildren(TabComponent) returns two tabs. Why does this work?
Show answer
The parent's template declares and creates the two app-tab components when it renders the host, whether or not any slot projects them. A content query finds nodes by where the parent declared them, so it sees both instances even though nothing is displayed.