Sub topic 9
Querying the Template with Signal Queries
Sometimes a component needs a direct handle on something in its template, such as an input element to focus, a child component to call a method on, or the list of tabs a user projected into it. Angular calls these lookups queries. Signal queries return their results as signals. Your code can then read them in computed() and effect() like any other reactive value, and they update by themselves when the template changes.
This chapter assumes you know how to build components with templates and content projection (<ng-content>). It also assumes you have read the earlier chapters on computed(), effect(), and input().
The four query functions
Angular has two kinds of query, each in a single-result form and a multiple-result form:
- View queries look inside the component's own template.
- Content queries look inside the content that a parent projects between the component's tags.
| Function | Searches | Returns | Replaces decorator | Column |
|---|---|---|---|---|
| `viewChild()` | Own template | `Signal<T \ | undefined>` | `@ViewChild` |
| `viewChild.required()` | Own template | `Signal<T>` | `@ViewChild` | |
| `viewChildren()` | Own template | `Signal<ReadonlyArray<T>>` | `@ViewChildren` | |
| `contentChild()` | Projected content | `Signal<T \ | undefined>` | `@ContentChild` |
| `contentChild.required()` | Projected content | `Signal<T>` | `@ContentChild` | |
| `contentChildren()` | Projected content | `Signal<ReadonlyArray<T>>` | `@ContentChildren` |
Every query takes a locator as its first argument. A locator is either a template reference variable name as a string ('nameInput' matches #nameInput) or a component or directive class (TabComponent). An optional second argument holds options, which this chapter covers below.
A first view query
The example below finds an <input> by its template reference and focuses it once the view has rendered:
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
@Component({
selector: 'app-name-field',
template: `<input #nameInput placeholder="Name" />`,
})
export class NameFieldComponent {
nameInput = viewChild.required<ElementRef<HTMLInputElement>>('nameInput');
constructor() {
afterNextRender(() => this.nameInput().nativeElement.focus());
}
}You read the query by calling it, just like any signal: this.nameInput(). When the locator is a string that names a plain DOM element, the result is an ElementRef wrapping that element. The generic parameter tells TypeScript what type to expect. Angular does not check that type at runtime, so make sure it matches what the template actually contains.
afterNextRender registers a callback that runs once, after Angular has rendered the component to the DOM. At that point the query has resolved and the element exists in the document, so DOM work like focus() or measuring is safe.
When query results become available
Queries are resolved during change detection, after Angular creates the template. Before that, nothing exists to find. This timing causes the most common query bug.
Here is what each stage means for your code:
- In the constructor or a field initializer, an optional query returns
undefined. A required query throws error NG0951, which says the required query has no result yet. Defining the query in a field is fine. Calling it at that point is the mistake. - In
computed()andeffect(), reading a query is safe. An optional query starts asundefined(or an empty array for the plural forms), and dependents re-run once the result arrives. Acomputed()you read only from the template is also safe, because the template reads it after the query has resolved. - In
afterNextRenderorngAfterViewInit, view query results are present. Use these for DOM work.
Signal queries have no static: true option like the old decorators did. Every signal query resolves during change detection. If you used static: true to read a query in ngOnInit, move that code into an effect or into afterNextRender.
Required versus optional
Use .required() when the target always exists in the template, as with an element outside any @if. Then the signal's type is T instead of T | undefined, and you avoid null checks. Use the optional form whenever the target can be missing:
import { Component, ElementRef, computed, signal, viewChild } from '@angular/core';
@Component({
selector: 'app-details',
template: `
<button (click)="open.set(!open())">Toggle</button>
@if (open()) {
<section #panel>Details go here</section>
}
<p>Panel rendered: {{ hasPanel() }}</p>
`,
})
export class DetailsComponent {
open = signal(false);
panel = viewChild<ElementRef<HTMLElement>>('panel');
hasPanel = computed(() => this.panel() !== undefined);
}When open turns true, the <section> is created, the query updates, and hasPanel() becomes true. When the section is removed, the query goes back to undefined. If you made this query required, the error would appear as soon as the panel is closed.
Choosing what you get back with `read`
By default a query returns the most specific thing at the match. For a component host, that is the component instance. For a plain element, it is an ElementRef. The read option asks for something else from the same node:
import { Component, ElementRef, ViewContainerRef, viewChild } from '@angular/core';
@Component({
selector: 'app-badge',
template: `<span>New</span>`,
})
export class BadgeComponent {}
@Component({
selector: 'app-host',
imports: [BadgeComponent],
template: `
<app-badge #badge />
<ng-container #slot />
`,
})
export class HostComponent {
badgeInstance = viewChild.required(BadgeComponent);
badgeElement = viewChild.required('badge', { read: ElementRef });
slot = viewChild.required('slot', { read: ViewContainerRef });
}badgeInstance() is the BadgeComponent object. badgeElement() is the <app-badge> host element. slot() is a ViewContainerRef you can use to create components dynamically. When you pass read, TypeScript infers the result type from it, so you do not need a generic.
Multiple results with `viewChildren()`
viewChildren() returns a read-only array that updates whenever matching elements are added, removed, or reordered. Combined with @for, it gives you a live list of rendered nodes:
import { Component, ElementRef, effect, signal, viewChildren } from '@angular/core';
@Component({
selector: 'app-chat',
template: `
<div class="log">
@for (msg of messages(); track $index) {
<p #line>{{ msg }}</p>
}
</div>
<button (click)="send()">Send</button>
`,
})
export class ChatComponent {
messages = signal<string[]>(['Hello']);
lines = viewChildren<ElementRef<HTMLParagraphElement>>('line');
constructor() {
effect(() => {
const all = this.lines();
all.at(-1)?.nativeElement.scrollIntoView({ block: 'end' });
});
}
send() {
this.messages.update(m => [...m, `Message ${m.length + 1}`]);
}
}The effect depends on lines, so it re-runs after each new paragraph is rendered and scrolls to the last one. It does not depend on messages. Reacting to the query and not the data means the DOM node is guaranteed to exist when the effect runs.
Content queries: `contentChild()` and `contentChildren()`
Content queries find what a parent places between your component's tags. A tab group is the classic case: the user writes <app-tab> elements, and the group needs to know about them.
import { Component, computed, contentChildren, effect, input, signal } from '@angular/core';
@Component({
selector: 'app-tab',
template: `@if (active()) { <ng-content /> }`,
})
export class TabComponent {
title = input.required<string>();
active = signal(false);
}
@Component({
selector: 'app-tabs',
template: `
<nav>
@for (tab of tabs(); track tab; let i = $index) {
<button [class.active]="i === selected()" (click)="selected.set(i)">
{{ tab.title() }}
</button>
}
</nav>
<p>{{ count() }} tabs</p>
<ng-content />
`,
})
export class TabsComponent {
tabs = contentChildren(TabComponent);
selected = signal(0);
count = computed(() => this.tabs().length);
constructor() {
effect(() => {
const index = this.selected();
this.tabs().forEach((tab, i) => tab.active.set(i === index));
});
}
}
@Component({
selector: 'app-root',
imports: [TabsComponent, TabComponent],
template: `
<app-tabs>
<app-tab title="Profile">Profile settings</app-tab>
<app-tab title="Billing">Billing details</app-tab>
</app-tabs>
`,
})
export class AppComponent {}The effect reads both selected and tabs, so it re-runs when the user picks a tab and also when a tab is added or removed. Because the query result is a signal, the tab bar, the count, and the active state all stay in sync without lifecycle hooks.
The `descendants` option
Content queries have one more option. descendants controls whether the search goes past direct children of the projected content:
| Query | Default `descendants` | Meaning of the default |
|---|---|---|
| `contentChildren()` | `false` | Only direct children are found |
| `contentChild()` | `true` | Any depth is searched |
With the default, a <app-tab> wrapped in a <div> inside <app-tabs> is not found by contentChildren(TabComponent). Pass { descendants: true } if wrappers are allowed. Content queries never look inside another component's own template. They only search the markup the parent wrote.
Common errors
- Reading a query in the constructor. You get
undefined, or NG0951 for required queries. Move the read intocomputed(),effect(), orafterNextRender. - Making a conditional target required. A target inside
@if,@defer, or@forcan disappear, so use the optional form. - Mismatched generic type.
viewChild<MyComponent>('ref')on a plain<div #ref>gives you anElementRefat runtime while TypeScript believes it is a component. Use the class as the locator, orread, to get correct inference. - Assigning to the query. Query signals are read-only. To change what is shown, change the state that drives the template.
- Doing DOM measurement in a plain effect. For layout reads and writes, prefer
afterNextRenderorafterRenderEffectso the work runs after the DOM has been updated.
Exercise
A component's template contains @if (loggedIn()) { <app-avatar /> }. A developer writes avatar = viewChild.required(AvatarComponent); and reads this.avatar().name in the constructor. List both problems and give a correct version that exposes the avatar's name as a signal.
Show answer
First, the constructor runs before the template is created, so a required query throws NG0951 there. Second, the avatar sits inside @if, so it can be missing even after rendering, which makes .required() wrong. Use avatar = viewChild(AvatarComponent); and avatarName = computed(() => this.avatar()?.name);. The computed value is undefined until the avatar renders and updates whenever the avatar appears or disappears.
Exercise
A MenuComponent declares items = contentChildren(MenuItemComponent);. A user writes <app-menu><div class="group"><app-menu-item /></div></app-menu>, and items() is empty. Why, and how do you fix it?
Show answer
contentChildren() defaults to descendants: false, so it only matches direct children of the projected content. The <app-menu-item> is nested in a <div>. Change the query to contentChildren(MenuItemComponent, { descendants: true }).
Exercise
You need the host ElementRef of a child <app-chart #chart /> to measure its width, but viewChild('chart') gives you the ChartComponent instance. What do you change, and where should the measurement run?
Show answer
Pass the read option: chartEl = viewChild.required('chart', { read: ElementRef });. Measure inside afterNextRender(() => this.chartEl().nativeElement.getBoundingClientRect().width) so the element has been rendered and laid out.