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
Angular ViewChildren Decorator The ViewChildren decorator in Angular is used to query multiple elements or directives in the view DOM and gain a reference to them. It is particularly useful when you want to interact with multiple elements of the same type or group within a template. The ViewChildren decorator returns a QueryList
6 min read
What is View in AngularJS ? In AngularJS, the View is what the user can see on the webpage. In an application (as per the userâs choice), the chosen view is displayed. For this purpose, the ng-view directive is used, which allows the application to render the view. Any changes made in the view section of the application are re
7 min read
What is Angular Router? Angular Router is an important feature of the Angular framework that helps you to build rich and interactive single-page applications (SPAs) with multiple views. In this article, we'll learn in detail about Angular Router. PrerequisitesNPM or Node jsBasics of AngularBasics of RoutingCode editor ( e.
5 min read
Angular Components Overview Angular Components are the building blocks of Angular applications, containing the template, styles, and behavior of a part of the user interface. This article provides an overview of Angular components, including their structure, features, and how to create and use them effectively. Table of Conten
6 min read
Angular PrimeNG Tree Methods Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. It provides a lot of templates, components, theme designs, an extensive icon library, and much more.
5 min read
Purpose of the ngOnInit() method in Angular ngOnInit is a lifecycle hook in Angular that is called after the constructor is called and after the componentâs inputs have been initialized. It is used to perform any additional initialization that is required for the component. ngOnInit is commonly used to call services or to set up subscriptions
3 min read