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
How to use jQuery in Angular ?
In this tutorial, we will learn how we can use jQuery with Angular. There are two ways in which we can use jQuery with Angular as discussed below: Table of Content By installing jQuery using the npm commandUsing jQuery CDN to use itBy installing jQuery using the npm commandYou can install the jQuery
2 min read
How to use Mat-Dialog in Angular ?
Introduction:Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can downloa
3 min read
How to use *ngIf else in AngularJS ?
Introduction: The ngIf directive is used to show or hide parts of an angular application. It can be added to any tags, it is a normal HTML tag, template, or selectors. It is a structural directive meaning that it includes templates based on a condition constrained to boolean. When the expression eva
3 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
How to use bootstrap 4 in angular 2?
Bootstrap is an open-source toolkit for developing with HTML, CSS, and JS. The Bootstrap framework can be used together with modern JavaScript web & mobile frameworks like Angular. Bootstrap 4 is the newest version of Bootstrap, which is the most popular HTML, CSS, and JavaScript framework. This
2 min read
How to Create a new module in Angular ?
Modules are most important when it comes to building strong and scalable Angular applications. They help organize your code, promote modularity, and improve maintainability. It encourages collaboration among developers by grouping related components, directives, pipes, and services. In this article,
3 min read
How to iterate over Object in Angular ?
Objects consist of a set of key-value pairs, which are known as Properties. All Properties are named in JavaScript objects and the key part represents the Property name, while the value part represents the property Value. Each element(key-value pair) of the object can be utilized to perform a specif
3 min read
Angular PrimeNG TabView Icons
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. In this article, we will know how to use the TabView Icons in Angular PrimeNG. We will also learn ab
3 min read
Why do we use $rootScope.$broadcast in AngularJS?
The $rootScope.$broadcast is used to broadcast a "global" event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.$on. Syntax: $rootScope.$broadcast(name, args)$scope.$on(name, listener);Parameter value: listener: It is
2 min read
How to Enable Webcam in Angular 10 using ngx-webcam ?
ngx-webcam component provides access of webcam to take snapshots simply via actions and event-bindings in Angular 10. This component gives us full control and permission to capture images in an easy way. Steps to add webcam to your application: Install Angular 10Create a Angular CLI ProjectInstall t
2 min read