How To Use ViewChild in Angular?
Last Updated :
12 Oct, 2024
In Angular, ViewChild is a powerful decorator that allows you to access and manipulate child components, directives, or DOM elements from a parent component. This feature is essential for scenarios where the parent needs to interact with its child components directly, such as invoking methods, accessing properties, or managing state.
Steps to use ViewCHild in Angular
Step 1: Create the Angular Application
If you haven't created an Angular application yet, you can set one up using Angular CLI:
ng new viewchild-demo
cd viewchild-demo
Project Structure:
Project StructureStep 2: Create a Child Component
Generate a child component where you’ll use ViewChild:
ng generate component child
Updated Dependencies:
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"lodash": "^4.17.21",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
This command will create a new folder child with the necessary files.
Step 3: Update the Child Component
Open child.component.ts and add a method and a property that we will access from the parent component.
JavaScript
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
// Make sure this is true for standalone components
template: `<h2>Child Component</h2>
<p>{{ message }}</p>
<button (click)="changeMessage()">Change Message</button>`,
})
export class ChildComponent {
message: string = 'Hello from Child!';
changeMessage() {
this.message = 'Message changed!';
}
}
Step 4: Update the Parent Component
Next, open app.component.ts (the default parent component) and use ViewChild to access the child component.
JavaScript
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Component({
selector: 'app-root',
standalone: true,
template: `<h1>Parent Component</h1>
<app-child></app-child>
<button (click)="callChildMethod()">Call Child Method</button>`,
imports: [ChildComponent],
})
export class AppComponent {
@ViewChild(ChildComponent) child!: ChildComponent;
callChildMethod() {
if (this.child) {
this.child.changeMessage();
}
}
}
Step 5: Update the App Module
Make sure the ChildComponent is declared in your app.module.ts. It should already be there if you generated the component properly:
JavaScript
import { isStandalone, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ChildComponent } from './child/child.component';
@NgModule({
declarations: [
AppComponent,
ChildComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 6: Run the Application
Now that everything is set up, run your application if it isn't already running:
ng serve
Output:
How It Works
- Child Component: The ChildComponent has a message that can be changed via a button click.
- Parent Component: The AppComponent uses ViewChild to access the ChildComponent instance. The callChildMethod() function calls the changeMessage() method from the ChildComponent, changing the message displayed there.
Why Use ViewChild?
- Encapsulation: It enables you to keep child components encapsulated while still allowing the parent to interact with them.
- Dynamic Interaction: You can respond to user actions in the parent component and dynamically change the behavior or data in the child component.
- Improved Performance: Direct access to child components can sometimes lead to performance benefits over event emitters, especially in complex component hierarchies.
Common Use Cases
- Accessing Methods: Call a method defined in a child component when an event occurs in the parent.
- Manipulating Data: Change properties in the child component based on user input or events in the parent.
- DOM Manipulation: Access native DOM elements to perform low-level operations.
Conclusion
- Use @ViewChild to reference a child component.
- You can call methods or access properties on the child component from the parent.
- Ensure that your child component is declared in the parent module.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read