📖 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
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
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
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
Hint
Use the ngAfterViewInit lifecycle hook to safely access the view child after the view is initialized.
Practice
(1/5)
1. What is the primary purpose of the @ViewChild decorator in Angular?
easy
A. To get a reference to a template element or child component
B. To create a new Angular module
C. To define routes in the application
D. To style components dynamically
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 A
Quick Check:
@ViewChild = Reference to template element [OK]
Hint: Remember: @ViewChild grabs template elements or child components [OK]
Common Mistakes:
Confusing @ViewChild with routing or module decorators
Thinking @ViewChild creates components
Assuming @ViewChild styles elements
2. Which of the following is the correct syntax to use @ViewChild to get a reference to a template element with template variable #myInput?
easy
A. @ViewChild(myInput) inputElement: ElementRef;
B. @ViewChild('myInput') inputElement: ElementRef;
C. @ViewChild(#myInput) inputElement: ElementRef;
D. @ViewChild('inputElement') myInput: ElementRef;
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 B
Quick Check:
Template variable name as string in @ViewChild [OK]
Hint: Always pass template variable name as a string in @ViewChild [OK]
Common Mistakes:
Omitting quotes around template variable name
Using # inside @ViewChild argument
Swapping variable names and template references
3. Given the following Angular component code, what will be logged to the console after the view initializes?
A. Accessing @ViewChild reference before view initialization
B. Missing quotes around 'myButton' in @ViewChild
C. Using ElementRef instead of TemplateRef
D. No error, code is correct
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 A
Quick Check:
@ViewChild ready only after ngAfterViewInit [OK]
Hint: Use ngAfterViewInit, not ngOnInit, to access @ViewChild [OK]
Common Mistakes:
Accessing @ViewChild in ngOnInit causing undefined errors
Confusing lifecycle hooks for view queries
Ignoring the timing of template element availability
5. You want to call a method focusInput() on a child component ChildComponent using @ViewChild. Which of the following is the correct way to do this safely after the view initializes?
hard
A. Use @ViewChild(ChildComponent) child: ElementRef; and call this.child.nativeElement.focusInput() inside ngAfterViewInit()
B. Use @ViewChild('child') child: ChildComponent; and call this.child.focusInput() inside constructor()
C. Use @ViewChild(ChildComponent) child!: ChildComponent; and call this.child.focusInput() inside ngAfterViewInit()
D. Use @ViewChild('child') child: ElementRef; and call this.child.focusInput() inside ngOnInit()
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 C
Quick Check:
Child component method call via @ViewChild after view init [OK]
Hint: Use component class in @ViewChild and call methods after ngAfterViewInit [OK]
Common Mistakes:
Calling child methods in constructor or ngOnInit
Using ElementRef instead of component class for child components
Trying to access nativeElement for component methods
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.