Open In App

How To Use ViewChild in Angular?

Last Updated : 12 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

file
Project Structure

Step 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:

file

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.

Next Article
Article Tags :

Similar Reads