Master ViewChild Angular with this Comprehensive Step by Step Tutorial

Article by: Manish Methani

Last Updated: September 15, 2021 at 8:04am IST
8 min 21 sec

Table of Contents:

Introduction:

ViewChild is a powerful feature in Angular that allows you to access and manipulate child components and DOM elements within your Angular templates. In this tutorial, we will walk you through the process of using ViewChild in Angular with practical examples.

Step 1: Prerequisites

Before we start, make sure you have the following prerequisites installed:

  • Node.js and npm: Download and install Node.js from nodejs.org.
  • Angular CLI: Install the Angular CLI globally by running npm install -g @angular/cli.

Final Output

Step 2: Create a New Angular Project

Open your terminal and create a new Angular project by running the following commands:

ng new view-child-demo 
 cd view-child-demo 
sudo npm install 

Step 3: Create a Child Component

In this tutorial, we will create a simple child component. Generate a new component called "child" using the Angular CLI:

ng generate component child 

Step 4: Use ViewChild in the Parent Component

Open the parent component's TypeScript file (app.component.ts) and import ViewChild from @angular/core. Then, define a reference to the child component using @ViewChild. Create an HTML template file for the parent component (app.component.html).

app.component.ts:

import { Component, ViewChild } from "@angular/core";
import { ChildComponent } from "./child/child.component";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
})
export class AppComponent {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  changeChildText() {
    this.childComponent.changeText();
  }
}

Step 5: Modify the Child Component

Open the child component's TypeScript file (child.component.ts) and add a method to change the text content. Create an HTML template file for the child component (child.component.html).

child.component.ts:

import { Component } from "@angular/core";

@Component({
  selector: "app-child",
  templateUrl: "./child.component.html",
})
export class ChildComponent {
  childText = "Hello from Child Component";

  changeText() {
    this.childText = "Text Updated by ViewChild";
  }
}

Step 6: Create HTML Templates

Now, let's create the HTML templates for both the parent and child components.

app.component.html:

  <h1>Using ViewChild in Angular</h1>
  <app-child></app-child>
  <button (click)="changeChildText()">Change Child Text</button>

Change Child Text

child.component.html:

<p>{{ childText }}</p>

Step 7: Display the Result

>Run your Angular development server by running ng serve and open your browser to http://localhost:4200. You should see the "Change Child Text" button that, when clicked, updates the text in the child component.

Final Output

If you are eager to take your web development skills to the next level, consider enrolling in the Full Stack Web Development course at Codzify. This comprehensive course covers everything you need to excel in web development. Become a certified Full Stack Web Developer.

FAQs:

FAQ

1. What is ViewChild in Angular?

ViewChild is a decorator in Angular that allows you to access child components, directives, or DOM elements in your Angular templates. It provides a way to interact with elements within your components view.

2. When should I use ViewChild in Angular?

You should use ViewChild when you need to perform actions on or retrieve data from child components or DOM elements within your Angular component. Its commonly used for scenarios like:

  • Accessing child component properties or methods.
  • Manipulating the DOM, such as changing element content or styles.
  • Retrieving references to form controls and performing validation.

3. How do I import ViewChild in Angular?

You can import ViewChild from `@angular/core`. Heres an example of importing it:

                
import { ViewChild } from "@angular/core";
                
            

4. Can I use ViewChild to access multiple elements?

Yes, you can use ViewChild to access multiple elements by using @ViewChildren. This allows you to query for multiple child components or elements that match a specific criteria.

5. Is ViewChild the same as ElementRef?

No, they are not the same. ViewChild is used to access child components and elements defined within Angular templates, while ElementRef is used to directly manipulate DOM elements outside the Angular template.

6. When should I use ElementRef?

You should use ElementRef when you need to directly manipulate DOM elements in a way that Angulars data binding and lifecycle hooks cannot achieve. However, it should be used with caution, as it bypasses Angulars change detection.

7. Is ViewChild safe to use?

Yes, ViewChild is safe to use when used properly. Angular ensures that ViewChild references are initialized after the view has been initialized, making it a safe way to access child components or DOM elements.

8. Can I use ViewChild with Angular content projection (ng-content)?

Yes, you can use ViewChild with components that use content projection (ng-content). You can access projected content by querying for elements within the child components view.

9. Can I use ViewChild with Angular services?

No, ViewChild is primarily used for accessing components, directives, and DOM elements within the components view. To communicate with services, its recommended to use Angulars dependency injection.

10. Where can I learn more about ViewChild in Angular?

For more in-depth information and examples, you can refer to the official Angular documentation on ViewChild and explore related resources and tutorials.

Explore Tech Guide:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com