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.
Practice
@ViewChild decorator in Angular?Solution
Step 1: Understand the role of @ViewChild
@ViewChild is used to access a child element or component from the template directly in the class.Step 2: Compare with other options
Creating modules, defining routes, or styling are unrelated to @ViewChild's purpose.Final Answer:
To get a reference to a template element or child component -> Option AQuick Check:
@ViewChild = Reference to template element [OK]
- Confusing @ViewChild with routing or module decorators
- Thinking @ViewChild creates components
- Assuming @ViewChild styles elements
@ViewChild to get a reference to a template element with template variable #myInput?Solution
Step 1: Check correct string usage in @ViewChild
The template variable name must be passed as a string, so it should be '@ViewChild('myInput')'.Step 2: Validate variable names and types
The variable name in the class can be anything, here 'inputElement', and type should be ElementRef for native elements.Final Answer:
@ViewChild('myInput') inputElement: ElementRef; -> Option BQuick Check:
Template variable name as string in @ViewChild [OK]
- Omitting quotes around template variable name
- Using # inside @ViewChild argument
- Swapping variable names and template references
<input #myInput type="text" value="Hello">
export class MyComponent implements AfterViewInit {
@ViewChild('myInput') inputRef!: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
console.log(this.inputRef.nativeElement.value);
}
}Solution
Step 1: Understand @ViewChild and ngAfterViewInit timing
@ViewChild gets the input element reference, and ngAfterViewInit runs after the view is ready, so inputRef is defined.Step 2: Access nativeElement value
inputRef.nativeElement.value accesses the input's value attribute, which is 'Hello'.Final Answer:
Hello -> Option DQuick Check:
Access input value via @ViewChild after view init [OK]
- Trying to access @ViewChild in constructor or ngOnInit
- Assuming inputRef is null or undefined after view init
- Confusing nativeElement with the ElementRef itself
@ViewChild: export class MyComponent {
@ViewChild('myButton') buttonRef: ElementRef;
ngOnInit() {
this.buttonRef.nativeElement.click();
}
}Solution
Step 1: Check lifecycle hook used
ngOnInit runs before the view is fully initialized, so @ViewChild references are not ready yet.Step 2: Correct lifecycle hook for @ViewChild access
Accessing @ViewChild should be done in ngAfterViewInit to ensure the element exists.Final Answer:
Accessing @ViewChild reference before view initialization -> Option AQuick Check:
@ViewChild ready only after ngAfterViewInit [OK]
- Accessing @ViewChild in ngOnInit causing undefined errors
- Confusing lifecycle hooks for view queries
- Ignoring the timing of template element availability
focusInput() on a child component ChildComponent using @ViewChild. Which of the following is the correct way to do this safely after the view initializes?Solution
Step 1: Correct @ViewChild usage for child component
Use the component class type in @ViewChild to get the child component instance, e.g. @ViewChild(ChildComponent).Step 2: Call child method after view initialization
Call the method inside ngAfterViewInit to ensure the child component is ready.Final Answer:
Use @ViewChild(ChildComponent) child!: ChildComponent; and call this.child.focusInput() inside ngAfterViewInit() -> Option CQuick Check:
Child component method call via @ViewChild after view init [OK]
- Calling child methods in constructor or ngOnInit
- Using ElementRef instead of component class for child components
- Trying to access nativeElement for component methods
Ready to prove it?
Pass the test and this pattern moves unknown
