0
0
Angularframework~3 mins

Why @ViewChild decorator usage in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple decorator can save you from messy and buggy DOM code!

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
const input = document.querySelector('#myInput'); input.value = 'Hello';
After
@ViewChild('myInput') inputRef: ElementRef;

ngAfterViewInit() {
  this.inputRef.nativeElement.value = 'Hello';
}
What It Enables

You can cleanly and safely interact with template elements or child components, making your code simpler and more reliable.

Real Life Example

For example, after a user submits a form, you can use @ViewChild to reset the input field or set focus back to it automatically.

Key Takeaways

@ViewChild helps you access template elements easily.

It avoids manual DOM queries and reduces bugs.

It keeps your Angular code clean and maintainable.