Sub topic 9
Querying the Template with Signal Queries
This chapter assumes you can build Angular components with templates, and that you already know computed(), effect(), and input() from earlier chapters. Experience with the older @ViewChild decorator is useful but not required.
What a signal query is
A query is a way for a component to get a reference to something in its template, such as a DOM element, a child component, or a directive. Angular provides four query functions. Each one returns a signal instead of assigning to a plain property.
| Function | Looks in | Returns | Column |
|---|---|---|---|
| `viewChild()` | The component's own template | `Signal<T \ | undefined>` |
| `viewChild.required()` | The component's own template | `Signal<T>` | |
| `viewChildren()` | The component's own template | `Signal<ReadonlyArray<T>>` | |
| `contentChild()` | Content projected through `<ng-content>` | `Signal<T \ | undefined>` |
| `contentChildren()` | Content projected through `<ng-content>` | `Signal<ReadonlyArray<T>>` |
The result is a signal, so it works the same way as every other signal in this tutorial. You read it by calling it, and a computed() or effect() that reads it re-runs when the query result changes. For example, the result changes when an @if block adds or removes the queried element.
Querying an element in your own view
The locator can be a template reference variable, given as a string, or a component or directive class. The component below finds an input by its #nameInput reference and focuses it.
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());
}
}viewChild.required drops undefined from the type, so you don't need ?. checks. In exchange, Angular throws an error if you read the query before it has resolved or if the element doesn't exist. afterNextRender runs its callback once the view has rendered, so the query has resolved by then and it is safe to touch the DOM.
Querying projected content
contentChildren() finds elements that a parent places between your component's tags. Here a tabs component counts and labels the tabs it receives:
import { Component, computed, contentChildren, input } from '@angular/core';
@Component({ selector: 'app-tab', template: `<ng-content />` })
export class TabComponent {
title = input.required<string>();
}
@Component({
selector: 'app-tabs',
template: `
<nav>
@for (tab of tabs(); track tab) {
<span>{{ tab.title() }}</span>
}
</nav>
<p>{{ count() }} tabs</p>
<ng-content />
`,
})
export class TabsComponent {
tabs = contentChildren(TabComponent);
count = computed(() => this.tabs().length);
}If the parent adds a tab with @if, the tabs signal updates. Then count and the nav update with it, and you don't need to subscribe to anything. By default, content queries match only direct children. Pass { descendants: true } to search deeper.
Useful options
readpicks which token to return for the matched node. For example,viewChild('box', { read: ElementRef })returns the element even when a component sits on it.descendantsapplies only to content queries and controls how deep the search goes.
Common mistakes
- Reading too early. This is the timing problem from the warning above.
- Treating the array as mutable.
viewChildrenreturns aReadonlyArray. To get a new list, derive it withcomputed(). - Mismatched locator names. If the string
'nameInput'doesn't match#nameInputexactly, an optional query staysundefinedand Angular reports no error. - Leftover decorator habits. Signal queries don't use
ngAfterViewInitorQueryList.changes. Reacting to the signal replaces both.
Exercise
A component declares panel = viewChild<ElementRef>('panel') and the template shows <div #panel> only inside @if (open()). What does panel() return when open() is false, and how would you log the element's width each time it appears?
Show answer
It returns undefined, because the element isn't rendered. Create an effect in the constructor, for example effect(() => { const el = this.panel(); if (el) console.log(el.nativeElement.offsetWidth); }). The effect re-runs whenever the query result changes, so it logs each time the panel appears.
Exercise
Why does viewChild.required('x') throw when you read it in the constructor, while the same read inside afterNextRender works?
Show answer
Queries resolve only after Angular creates the component's view, and that happens after the constructor runs. afterNextRender runs once the view has rendered, so by then the required query has a value.