Angular14 min read
ViewChild: Access DOM Elements and Child Components
Use @ViewChild to focus inputs, call child component methods, and integrate UI behaviors safely.
Zoe Richardson
September 15, 2025
7.3k149
@ViewChild lets you reference an element or a child component instance from your template.
Example: focus an input after page load
Template:
<input #searchInput placeholder="Search..." />
<button (click)="focus()">Focus Input</button>
Component:
import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-search',
standalone: true,
templateUrl: './search.component.html',
})
export class SearchComponent implements AfterViewInit {
@ViewChild('searchInput') searchInput?: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
this.searchInput?.nativeElement.focus();
}
focus() {
this.searchInput?.nativeElement.focus();
}
}
Best practice
Use ViewChild only when needed. Most UI should be controlled through binding, not direct DOM access.
Next: Change detection basics and why performance sometimes feels “mysterious.”
#Angular#Components#Intermediate