ViewChild Decorator

Overview

The @ViewChild decorator is a powerful tool that enables you to access and manipulate child components, elements, and directives from a parent component. In this chapter, we will delve into the concept of @ViewChild, explaining its used, and provide practical examples to illustrate how it can be effectively utilized in Angular applications.

Understanding @ViewChild

The @ViewChild decorator is used to query and access child components, elements, or directives in the template of a parent component. It provides a way to establish communication between parent and child components, access child component properties and methods, and perform dynamic manipulation.

Declaring @ViewChild

To use @ViewChild , you declare it as a class property within your component. You specify the type of the item you want to access and provide an optional selector to identify the specific element or component. Here's basic example:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: '<app-child></app-child>',
})
export class ParentComponent {
  @ViewChild(AppChildComponent) childComponent: AppChildComponent;
  @ViewChild('myInput') inputElement: ElementRef;
}

In this example:

  • @ViewChild(AppChildComponent) accesses the AppChildComponent child component.
  • @ViewChild('myInput') accesses an element with the template reference variable #myInput.

Assessing and Interacting with Child Components

Once you have defined @ViewChild properties, you can access and interact with child components directly in your component class. This is useful for performing actions, retrieving data, or coordinating behavior between components.

ngAfterViewInit() {
  // Accessing child component's methods or properties
  this.childComponent.someMethod();
  this.childComponent.someProperty = 'New Value';

  // Accessing and manipulating the DOM element
  this.inputElement.nativeElement.value = 'Updated Value';
}