What is ViewChild in Angular: Simple Explanation and Example
ViewChild in Angular is a decorator that lets you get a reference to a child component, directive, or DOM element inside your component class. It helps you access and control that child directly in your TypeScript code after the view is initialized.How It Works
Imagine you have a parent component that contains a child component or an HTML element, like a button. Sometimes, you want to interact with that child directly from the parent’s code, for example, to change its properties or call its methods.
ViewChild works like a bridge that connects your parent component class to a specific child element or component inside its template. When Angular builds the view, it finds the child you asked for and gives you a direct reference to it.
This is similar to having a remote control for a device in your living room. Instead of walking over to the device, you use the remote (the ViewChild) to control it from where you are.
Example
This example shows how to use ViewChild to access a button element and change its text when a method runs.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-root', template: ` <button #myButton>Click me</button> <button (click)="changeButtonText()">Change Text</button> ` }) export class AppComponent implements AfterViewInit { @ViewChild('myButton') button!: ElementRef<HTMLButtonElement>; ngAfterViewInit() { // ViewChild is set after view initialization } changeButtonText() { this.button.nativeElement.textContent = 'Text Changed!'; } }
When to Use
Use ViewChild when you need to directly access or control a child component, directive, or DOM element from your component class. This is useful for:
- Calling methods on a child component to trigger actions.
- Changing properties or styles of a DOM element dynamically.
- Accessing template elements that Angular does not expose automatically.
For example, you might want to focus an input field after a form loads or reset a child component’s state from the parent.
Key Points
- ViewChild gets a reference to a child component, directive, or element in the template.
- It works after the view is initialized, so use lifecycle hooks like
ngAfterViewInit. - It helps you control or read from the child directly in your TypeScript code.
- Use the template reference variable (like
#myButton) or component type to identify the child. - It is useful for dynamic UI changes and component interaction.
Key Takeaways
ViewChild lets you access child components or elements directly in your component class.ngAfterViewInit.