Discover how a simple decorator can save you from messy and buggy DOM code!
Why @ViewChild decorator usage in Angular? - Purpose & Use Cases
Imagine you have a form with many input fields and buttons, and you want to change the style or read values directly from one specific input after the page loads.
Without a simple way to grab that element, you might try to search the whole page manually or add complicated IDs and query selectors everywhere.
Manually searching and manipulating DOM elements is slow and error-prone.
You might select the wrong element, cause bugs, or write lots of repetitive code that is hard to maintain.
Also, it breaks Angular's clean structure and can cause unexpected behavior.
The @ViewChild decorator lets you easily get a reference to a specific element or component inside your template.
This means you can directly access and control that element in your TypeScript code without messy queries.
const input = document.querySelector('#myInput'); input.value = 'Hello';
@ViewChild('myInput') inputRef: ElementRef; ngAfterViewInit() { this.inputRef.nativeElement.value = 'Hello'; }
You can cleanly and safely interact with template elements or child components, making your code simpler and more reliable.
For example, after a user submits a form, you can use @ViewChild to reset the input field or set focus back to it automatically.
@ViewChild helps you access template elements easily.
It avoids manual DOM queries and reduces bugs.
It keeps your Angular code clean and maintainable.
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
