viewChild()

Queries a single element or directive from the component view as a signal.

Since Angular 17.2+ Spec ↗

Syntax

viewChild<T>(locator, options?) | viewChild.required<T>(locator, options?)

Parameters

NameTypeRequiredDescription
locator string | Type<T> No Template reference name or component/directive type to find.
options object No Supports read to select a specific token from the queried node.

Returns

Signal<T | undefined> — Signal of the matched query result, or required variant excluding undefined.

Examples

import { Component, viewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-box',
  standalone: true,
  template: `<input #field />`,
})
export class BoxComponent {
  field = viewChild<ElementRef<HTMLInputElement>>('field');
  focus() {
    this.field()?.nativeElement.focus();
  }
}

Notes

Signal queries resolve after the view initializes; reading before that yields undefined (unless using the .required form, which throws if not found). Use the `read` option to read a different token, e.g. ElementRef vs. a component instance.