Angular @ViewChild Directive And Components Interaction

In this article, we will focus on components interaction in Angular. Components are the most crucial part of an Angular application.

Components are the building blocks of an Angular application. Mostly, an Angular application is the combination of components. There are parent component and child components which make a tree-like structure.
Angular @ViewChild Directive and Components Interaction 

Components communicate with each other through a number of ways. ViewChild is used to access DOM elements in the template from the containing component class or parent component class. DOM elements in the template can be any element, directive, or child component. With ViewChild, a component class can get access to child component properties and methods.

To use it, we need to pass the template reference variable name, directive name, or child component class name as an argument. It returns the first element that matches the selector defined in the ViewChild and its properties and methods are accessible in ngAfterViewInit() lifecycle hook.

Let's understand this with a simple example. Suppose, we have a login page having username and password fields. The goal is when the page loads, the username is focused. To achieve this, attach a template reference variable named “userNameRef” to username input field.

Login.component.html

  1. <form>  
  2.     <div class="form-group">  
  3.         <label>Username</label>  
  4.         <input #userNameRef type="text" class="form-control" [(ngModel)]="userName">  
  5.     </div>  
  6.     <div class="form-group">  
  7.         <label>Password</label>  
  8.         <input type="text" class="form-control" [(ngModel)]="password">  
  9.     </div>  
  10.     <button type="submit" class="btn btn-success">Submit</button>  
  11. </form>  

In the component class, create a property of type “ElementRef” that will hold the reference of this DOM element. In the ngAfterViewInit() lifecycle hook, get the reference variable and apply focus on it.

Login.component.ts

  1. import { Component, ElementRef ViewChild, AfterViewInit } from '@angular/core';  
  2. @Component({  
  3.    selector: 'login-component',  
  4.    templateUrl: './login.component.html'  
  5. })  
  6. export class LoginComponent implements AfterViewInit{  
  7.    @ViewChild('userNameRef') userNameRef : ElementRef;  
  8.    ngAfterViewInit(){  
  9.       this.userNameRef.nativeElement.focus();  
  10.    }  
  11. }  

We have seen that @ViewChild is a very useful directive in Angular. But if we want to access multiple child references, then we have to use @ViewChildren.


Similar Articles