0
0
Angularframework~30 mins

@ViewChild decorator usage in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
@ViewChild Decorator Usage in Angular
📖 Scenario: You are building a simple Angular component that needs to access a button element inside its template to change its text dynamically.
🎯 Goal: Learn how to use the @ViewChild decorator to get a reference to a template element and update its properties in the component class.
📋 What You'll Learn
Create a button element in the component template with a template reference variable.
Use the @ViewChild decorator to get the button element in the component class.
Create a method to change the button text using the @ViewChild reference.
Call the method after the view initializes to update the button text.
💡 Why This Matters
🌍 Real World
Accessing and manipulating DOM elements or child components directly is common in Angular apps for dynamic UI updates, animations, or integrating third-party libraries.
💼 Career
Understanding @ViewChild is essential for Angular developers to interact with template elements and child components, enabling more interactive and responsive applications.
Progress0 / 4 steps
1
Create a button with a template reference variable
In the component template, create a <button> element with the template reference variable #myButton and the initial text Click me.
Angular
Need a hint?

Use #myButton inside the button tag to create a template reference variable.

2
Add @ViewChild to get the button element
In the component TypeScript file, import ViewChild and ElementRef from @angular/core. Then declare a property called myButton using @ViewChild('myButton') with type ElementRef<HTMLButtonElement>.
Angular
Need a hint?

Use @ViewChild('myButton') to get the button element by its template reference variable.

3
Create a method to change the button text
Add a method called changeButtonText inside the component class. Inside this method, use this.myButton.nativeElement.textContent = 'Updated!' to change the button text.
Angular
Need a hint?

Use this.myButton.nativeElement.textContent to update the button's text.

4
Call the method after view initialization
Implement the ngAfterViewInit lifecycle hook in the component class. Inside it, call the changeButtonText() method to update the button text after the view loads.
Angular
Need a hint?

Use the ngAfterViewInit lifecycle hook to safely access the view child after the view is initialized.