Sub topic 15
Accessing Children with viewChild and contentChild
This chapter assumes you already know template reference variables, content projection with ng-content, and how to read signals in templates.
A template can usually talk to its children through inputs and outputs. Sometimes the class needs a direct handle instead, for example to call a method on a child component or to focus an element. Queries give you that handle.
View Children Versus Content Children
A component has two kinds of children:
- View children are elements and components written in the component's own template.
- Content children are elements a parent projects in between the component's tags, which reach the page through
ng-content.
Querying the View with viewChild
Pass viewChild a component class or the name of a template reference variable. It returns a signal holding the match.
import { Component, signal, viewChild } from '@angular/core';
@Component({
selector: 'app-timer',
template: `{{ seconds() }}s <button (click)="tick()">+1</button>`
})
export class TimerComponent {
seconds = signal(0);
tick() { this.seconds.update(s => s + 1); }
reset() { this.seconds.set(0); }
}
@Component({
selector: 'app-dashboard',
imports: [TimerComponent],
template: `
<app-timer />
<button (click)="resetTimer()">Reset</button>
`
})
export class DashboardComponent {
timer = viewChild.required(TimerComponent);
resetTimer() {
this.timer().reset();
}
}viewChild.required tells Angular the match always exists, so the signal's type does not include undefined. If the child sits inside an @if, use plain viewChild and handle the undefined case. To get every match, use viewChildren, which returns a signal of a read-only array that updates as @for adds or removes items.
Querying Projected Content with contentChild
contentChild searches what the parent placed between your tags:
import { Component, ElementRef, contentChild } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<ng-content />
@if (!title()) {
<p>Untitled panel</p>
}
`
})
export class PanelComponent {
title = contentChild<ElementRef<HTMLElement>>('panelTitle');
}
// Usage:
// <app-panel><h2 #panelTitle>Stats</h2></app-panel>contentChildren returns all matches. By default it checks only direct children of the host. Pass { descendants: true } to search deeper.
Common Errors
| Problem | Cause | Fix |
|---|---|---|
| Value is `undefined` in the constructor | The view has not been created yet | Read the query in an event handler, a `computed`, an `effect`, or `ngAfterViewInit` |
| `viewChild` finds nothing for projected content | Projected elements belong to the content, not the view | Use `contentChild` |
| You get a component when you wanted the element | By default Angular returns the component instance | Pass `{ read: ElementRef }` |
| `.required` throws an error | The match is inside an `@if` that is currently false | Use the optional form |
Exercise
A TabsComponent must find every TabComponent that a parent places between <app-tabs> tags, including tabs wrapped in a <div>. Which query do you write?
Show answer
tabs = contentChildren(TabComponent, { descendants: true });. The tabs are projected content, so you need a content query. You need descendants: true because contentChildren checks only direct children by default, and that would miss the tabs inside the <div>.
Exercise
Why does this.timer() throw an error when it is called in DashboardComponent's constructor?
Show answer
The constructor runs before Angular creates the view, so <app-timer> does not exist yet. A required query throws an error when you read it before its result is available.