Angular 7 ViewChild Tutorial – Access Child Component

By Digamber Rawat Last updated on
Viewchild is one of the decorators in Angular 7. It is one of the basic ones, and you will learn about it in the early stages itself. We have to mention the fact that Viewchild in Angular 7 is one of the widely used decorators.Viewchild in Angular comes with many features. You will find these features useful. However, only a handful of features are prevalent.

If you wish to gain access to a DOM element, directive or component from a parent component class then you rely on Angular 7 Viewchild. When you run Viewchild in Angular 2, it will return the 1st element that matches. It will match against the template reference selector, directive or component. In case if you wish to retrieve multiple children, you will go for ViewChildren.

The best thing about Viewchild in Angular is that it is capable of handling dynamic reference changes. Viewchild will update the change. The nice thing too is that, if the reference changes to a new element dynamically, ViewChild in Angular 2 will take care of updating its reference automatically.

Angular 7 Directives

Let’s assume that we possess a GreetDirective:

directive > greet.directive.ts

import { Directive, ElementRef, Renderer2 } from '@angular/core';

@Directive(
  { selector: '[appGreet]' }
)

export class GreetDirective {
  WhatsUp = 'How Are You?';
  
  constructor(elem: ElementRef, renderer: Renderer2) {
    let greet = renderer.createText('Hello');
    renderer.appendChild(elem.nativeElement, greet);
  }
}

How to access the directive using ViewChild Angular 7?

Well, we need to look at the following code.

In the following example, we are going to access the ingredient instance variable. Also, we are going to assign the value to an extra ingredient instance variable.

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

import { GreetDirective } from './directive/greet.directive';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent {
  greetMe: string;

  @ViewChild(GreetDirective)
  
  set greetApp(dir: GreetDirective) {
    this.greetMe = dir.WhatsUp
  };

}

As you can see in the example, we took the help of a setter method and AfterViewInit. If you take a closer look at the snippet. The directives and child components were present only AfterViewInit life cycle hook is called.

Accessing DOM Elements using Angular 7 ViewChild

The DOM elements with a template reference variable can be accessed. We are going to assume we have it in our template.

<input #accessId placeholder="Whta's your name?">

We are going to access the input this way:

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

import { GreetDirective } from './directive/greet.directive';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent implements AfterViewInit {
  @ViewChild('accessId') accessId: ElementRef;
 
  ngAfterViewInit() {
    this.accessId.nativeElement.value = "Tony Stark";
  }
}

When ngAfterViewInit comes into play, the input value will be Tony Stark.

Angular 7 Viewchild & Child Components

We can easily access a child component. We will be able to access instance variables and call methods with ease. In the following example, howAreYou() is a method of a child component.

Now are going to call the howAreYou() method inside the AppComponent class.

app.component.ts

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

import { SubComponent } from './component/sub.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent implements AfterViewInit {
  @ViewChild(SubComponent) sub: SubComponent;

  ngAfterViewInit() {
    console.log(this.sub.howAreYou()); 
    // I am cool
  }
}

When Should We Use ViewChild Decorator in Angular 7?

We have the facility to use template references like #mainColor or #mainInput in the template. This way we will be able to coordinate HTML elements and components. We will be able to achieve this without using the AppComponent class.

However, it doesn’t work like this all the time. There are times when the AppComponent has to access multiple elements which belong to the template. This is to make sure that the interaction is possible.

This is precisely why need Angular @ViewChild for. We make it happen by querying the template.

We are going to examine how we can use Viewchild to input a reference.
Let’s take the example where AppComponent is going to refer to the <demo-color> component.

With the help of ViewChild in Angular 2, we will be able to input a reference to the instance called #mainColor.

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})

export class AppComponent {
  .....
 
  @ViewChild(mainColor)
  colorComponent: mainColor;
 
  .....
}

When we use ViewChild, mainColor instance comes into play. This instance is going to fill the member variable colorComponent.

Availability of variables injected

The value of the member variable is not available immediately. The value will be assigned only during the component lifecycle. This happens right after the completion of view initialization.

Conclusion

With the help of ViewChild decorator, we will be injecting into a class reference. Also, that is the primary purpose of ViewChild in Angular. With the help of ViewChild decorator, you will be able to inject DOM elements, directives or components. We will also be able to override the defaults. We can inject multiple things and inject the things we want to inject.

ViewChild cannot see internals when it comes to the child components. Thanks to ViewChild, it has become straightforward to write coordination logic.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me