liveBook · Manning

viewChild

As explained in Modern Angular

viewChild is an Angular query function that returns a signal containing a reference to a matching element or component in a component view.

`viewChild` is a signal-based query for accessing an HTML element or component from a component template. Rather than storing an `ElementRef` through the legacy `@ViewChild` decorator, it returns a signal containing the queried reference. section 10.3.4

Because the result is a signal, it can participate in reactive code: derive computed signals from a queried child or use it in effects as a tracked dependency. For collections, `viewChildren` also reacts when queried elements are added or removed. section 10.3.4

Query a template container

Replace a decorator property with a signal query: `containerDiv = viewChild<ElementRef<HTMLDivElement>>('container');`. The query targets the template reference named `container` and exposes its `ElementRef` through the resulting signal. section 10.3.4 section 10.3.4

Use `contentChild` or `contentChildren` when the target belongs to projected content rather than the component’s own template. The plural query functions provide arrays of matching elements or components. section 7.5.3 section 10.3.4

How Modern Angular covers it

How deep it goes
Explains signal-returning child queries and their computed, effect, and collection-update behavior without deeper implementation internals.
Examples
Contrasts `@ViewChild('container')` with `viewChild<ElementRef<HTMLDivElement>>('container')`.
What it assumes
Assumes familiarity with `@ViewChild`, `ElementRef`, component templates, and signals.
What you can do after
Apply it via Angular signal queries to access template elements or components reactively.
How it connects
Connects viewChild to signals, computed signals, effects, viewChildren, contentChild, and contentChildren.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.