The @ViewChild decorator helps you get a reference to a part of your template inside your component code. This lets you work with that part directly, like changing its properties or calling its methods.
@ViewChild decorator usage in Angular
import { ViewChild, ElementRef } from '@angular/core'; @Component({ ... }) export class MyComponent { @ViewChild('templateRefName') elementRef!: ElementRef; ngAfterViewInit() { // Use this.elementRef here } }
The string inside @ViewChild('templateRefName') matches the template reference variable in your HTML.
You usually access the element inside ngAfterViewInit() lifecycle hook to ensure the view is ready.
@ViewChild('myButton') button!: ElementRef<HTMLButtonElement>; ngAfterViewInit() { this.button.nativeElement.textContent = 'Clicked!'; }
@ViewChild(ChildComponent) childComp!: ChildComponent;
ngAfterViewInit() {
this.childComp.someMethod();
}@ViewChild.@ViewChild('inputBox') input!: ElementRef<HTMLInputElement>; focusInput() { this.input.nativeElement.focus(); }
This component uses @ViewChild to get references to a button and an input box. After the view loads, it changes the button text and focuses the input box automatically.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-root', template: ` <button #myBtn>Click me</button> <input #myInput type="text" placeholder="Type here" /> ` }) export class AppComponent implements AfterViewInit { @ViewChild('myBtn') button!: ElementRef<HTMLButtonElement>; @ViewChild('myInput') input!: ElementRef<HTMLInputElement>; ngAfterViewInit() { this.button.nativeElement.textContent = 'Ready to click'; this.input.nativeElement.focus(); } }
Always use ngAfterViewInit to access @ViewChild elements because the view is not ready in the constructor or ngOnInit.
If the element or component might not exist, use the { static: false } option (default) to avoid errors.
You can also use @ViewChild with a component class to get its instance, not just DOM elements.
@ViewChild lets you get a direct reference to a template element or child component.
Use it to change element properties, call child methods, or control focus.
Access the reference safely inside ngAfterViewInit lifecycle hook.