Sub topic 15
Accessing Children with viewChild and contentChild
A template reference variable gives the template a handle on an element. Sometimes the class needs that handle too. For example, the class may need to focus an input, call a method on a child component, or find out which tabs a user placed inside a container. Angular's queries give the class this access. A query is a declaration that tells Angular to find matching elements or components and keep a live reference to them.
This chapter assumes you know component inputs, template reference variables, content projection with ng-content, and how to read signals. All examples use Angular 19 or later, where components are standalone by default.
View Children Versus Content Children
A component can reach two groups of children, and each group has its own query functions.
- View children are elements and components written in the component's own template.
- Content children are elements and components that the parent places between the component's tags. They reach the component's template through
ng-content.
| Function | Searches | Returns | Column |
|---|---|---|---|
| `viewChild(locator)` | Own template | `Signal<T \ | undefined>` |
| `viewChild.required(locator)` | Own template | `Signal<T>` | |
| `viewChildren(locator)` | Own template | `Signal<ReadonlyArray<T>>` | |
| `contentChild(locator)` | Projected content | `Signal<T \ | undefined>` |
| `contentChild.required(locator)` | Projected content | `Signal<T>` | |
| `contentChildren(locator)` | Projected content | `Signal<ReadonlyArray<T>>` |
The locator is either a string or a type. A string matches a template reference variable name, such as 'query' for #query. A type matches every component or directive of that class, such as TabComponent.
Querying the Component's Own View
The following component queries one element by reference name and a list of child components by type.
import { Component, ElementRef, afterNextRender, input, viewChild, viewChildren } from '@angular/core';
@Component({
selector: 'app-row',
template: `<li>{{ name() }}</li>`
})
export class RowComponent {
name = input.required<string>();
highlight() {
console.log('Highlighting', this.name());
}
}
@Component({
selector: 'app-people',
imports: [RowComponent],
template: `
<input #filter placeholder="Filter people" />
<ul>
@for (person of people; track person) {
<app-row [name]="person" />
}
</ul>
<button (click)="highlightAll()">Highlight all</button>
`
})
export class PeopleComponent {
people = ['Ada', 'Grace', 'Linus'];
filter = viewChild.required<ElementRef<HTMLInputElement>>('filter');
rows = viewChildren(RowComponent);
constructor() {
afterNextRender(() => this.filter().nativeElement.focus());
}
highlightAll() {
this.rows().forEach(row => row.highlight());
}
}When the locator is a reference on a plain HTML element, you get an ElementRef, and its nativeElement property holds the DOM node. When the locator is a component type, you get the component instance itself, so you can call its public methods and read its signals.
afterNextRender runs once the browser has rendered the view. That makes it a safe place for DOM work such as focus().
Choosing What a Query Returns with read
A single match can be read in different ways. The read option tells Angular which one you want.
// The component instance (default when the locator is a type)
chart = viewChild(ChartComponent);
// The host DOM element of that component instead
chartElement = viewChild(ChartComponent, { read: ElementRef });
// A ViewContainerRef at that location, for creating views dynamically
slot = viewChild('slot', { read: ViewContainerRef });A reference on a component's host element (<app-chart #c />) resolves to the component instance by default. Use read: ElementRef when you need the DOM node.
Querying Projected Content
Content queries let a container component work with whatever the parent puts inside it. A tab set is the standard example: the parent writes the tabs, and the tab set builds buttons from them.
import { Component, contentChildren, effect, input, signal } from '@angular/core';
@Component({
selector: 'app-tab',
template: `@if (active()) { <ng-content /> }`
})
export class TabComponent {
label = input.required<string>();
active = signal(false);
}
@Component({
selector: 'app-tabs',
template: `
<nav>
@for (tab of tabs(); track tab; let i = $index) {
<button [class.selected]="tab.active()" (click)="select(i)">
{{ tab.label() }}
</button>
}
</nav>
<ng-content />
`,
styles: `.selected { font-weight: bold; }`
})
export class TabsComponent {
tabs = contentChildren(TabComponent);
constructor() {
effect(() => {
const tabs = this.tabs();
if (tabs.length > 0 && !tabs.some(t => t.active())) {
tabs[0].active.set(true);
}
});
}
select(index: number) {
this.tabs().forEach((tab, i) => tab.active.set(i === index));
}
}
@Component({
selector: 'app-account',
imports: [TabsComponent, TabComponent],
template: `
<app-tabs>
<app-tab label="Profile"><p>Your profile.</p></app-tab>
<app-tab label="Billing"><p>Your invoices.</p></app-tab>
</app-tabs>
`
})
export class AccountComponent {}tabs is a signal, so the @for loop and the effect both re-run when the parent adds or removes an app-tab, for example inside an @if. You don't need to subscribe to anything.
The descendants Option
By default, contentChildren only matches direct children of the host element. If a tab is wrapped in another element, such as <div><app-tab .../></div>, it is not found. Pass { descendants: true } to search deeper:
tabs = contentChildren(TabComponent, { descendants: true });contentChild (singular) searches descendants by default. Content queries never look inside the templates of other components. They only see the markup the parent wrote.
When Query Results Are Available
Queries resolve during change detection. That has three consequences:
- In the constructor, a query signal has not resolved yet. Reading an optional query gives
undefined. Reading a.requiredquery throws error NG0951. - View query results are ready by the time
ngAfterViewInitruns, and content query results byngAfterContentInit. The next chapter covers these hooks. - Results change over time. A match inside
@ifor@forappears and disappears as the condition or list changes. Read the signal insidecomputed,effect, or the template, so your code follows those changes.
The Decorator Forms
Older code and many libraries use decorators instead of signal functions. You should be able to read them:
import { AfterViewInit, Component, ContentChildren, ElementRef, QueryList, ViewChild } from '@angular/core';
import { TabComponent } from './tab.component';
@Component({
selector: 'app-legacy-tabs',
template: `<input #filter /><ng-content />`
})
export class LegacyTabsComponent implements AfterViewInit {
@ViewChild('filter', { static: true }) filter!: ElementRef<HTMLInputElement>;
@ContentChildren(TabComponent) tabs!: QueryList<TabComponent>;
ngAfterViewInit() {
this.filter.nativeElement.focus();
this.tabs.changes.subscribe(list => console.log('Tabs now:', list.length));
}
}The main differences from signal queries:
| Aspect | Decorator queries | Signal queries |
|---|---|---|
| Result type | Plain property, `QueryList` for lists | Signal, read-only array for lists |
| Reacting to changes | Subscribe to `QueryList.changes` | Use `computed` or `effect` |
| Early access | `static: true` makes results ready in `ngOnInit` if the match is outside control flow | No `static` option. Results are ready after the first change detection |
| Type safety | `!` assertion hides possible `undefined` | `undefined` is part of the type unless `.required` |
Common Mistakes
- Using
viewChildfor projected content. Elements the parent passes in are content, not view. UsecontentChildfor them. - Expecting
ElementReffrom a component reference.#con<app-chart>gives the component instance. Addread: ElementRefto get the DOM node. - Missing wrapped content children. Use
descendants: truewithcontentChildrenwhen matches are nested inside other elements. - Touching the DOM in the constructor. Use
afterNextRenderorafterRenderfor DOM work. - Using queries where an input would do. If a parent only needs to pass data to a child, bind an input. Use queries when the parent must call methods on children or find out what content it received.
Exercise
A DialogComponent template contains <div #body><ng-content /></div>. Users write <app-dialog><app-form /></app-dialog>. Which query should DialogComponent use to get the <div>, and which to get the AppFormComponent instance?
Show answer
The <div> is in the dialog's own template, so use viewChild<ElementRef<HTMLDivElement>>('body'). The app-form is written by the parent between the dialog's tags, so it is projected content: use contentChild(AppFormComponent).
Exercise
A tab set declares tabs = contentChildren(TabComponent), but it finds no tabs when used as <app-tabs><section><app-tab label="A" /></section></app-tabs>. Why, and how do you fix it?
Show answer
contentChildren matches only direct children by default, and here the tab is wrapped in a <section>. Change the declaration to contentChildren(TabComponent, { descendants: true }).
Exercise
Why does panel = viewChild.required<ElementRef>('panel') throw at runtime when #panel sits inside @if (open()) and open() starts as false?
Show answer
The element doesn't exist while the condition is false, so the required query has no result and throws NG0951 when read. Use the optional viewChild<ElementRef>('panel') and handle undefined.