All topics
Componentsintermediate

ViewChild and ViewChildren

Explain how @ViewChild and @ViewChildren give a component class imperative access to elements and child components in its own template.

@ViewChild and @ViewChildren let a component class reach into its own rendered view and grab a reference to a DOM element, a child component instance, or a directive instance, which is essential for the handful of cases where declarative binding isn't enough — focusing an input programmatically, calling an imperative API on a third-party widget, or measuring an element's dimensions.

It's like a stage manager who can't grab a prop until the set has actually been built — only once construction is finished (ngAfterViewInit) can they walk over and pick up the specific prop they need.

Key Concepts

1
The critical timing detail interviewers probe is that view children are not available in the constructor or ngOnInit — they're only guaranteed to be set by ngAfterViewInit, because that's the first point at which Angular guarantees the view (including child components) has been fully initialized. Accessing this.myRef before that point typically returns undefined.
ngOnInitngAfterViewInitthis.myRefundefined
2
@ViewChild returns a single reference (the first match), while @ViewChildren returns a QueryList, which is a live, observable collection that updates automatically if the matched elements change — for example, items added or removed from an *ngFor list. QueryList exposes a .changes Observable specifically so you can react to those additions/removals.
@ViewChild@ViewChildrenQueryList*ngFor.changes
3
Modern Angular offers a signal-based alternative, viewChild() and viewChildren(), which return signals instead of requiring the static: true/false option juggling that the decorator API needed, and which integrate cleanly with computed() and effect().
viewChild()viewChildren()static: true/falsecomputed()effect()