Welcome to the free & complete Angular Tutorial.

In this post, we are going to quickly learn how to use template reference variable to interact with Child component.

Components interaction is very helpful to exchange data between Parent and Child components using Input and Output decorators

Check it out in official Angular documentation in the Component interaction section.

Let’s get started.

Step 1: Create new Angular project

Create a new Angular project by running below command in Command prompt/ Bash/ Terminal:

ng new parent-child-template-ref-var

Step 2: Create a child component

Ok, let’s create a new component called Greet and add a method to display a text “Hola User” on browser window.

ng g c greet

greet.component.ts

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

@Component({
  selector: 'app-greet',
  templateUrl: './greet.component.html',
  styleUrls: ['./greet.component.css']
})
export class GreetComponent implements OnInit {

  displayTxt: boolean = false;
  
  constructor() { }

  ngOnInit(): void {
  }

  greetMe(){
    this.displayTxt = true;
  }
}

greet.component.html

<div *ngIf="displayTxt">
    Hello User!
</div>

Step 3: Invoke child component method from Parent component using template reference variable

Update app.component.html, which is a parent component in this example, to render child component in it.

app.component.html

<app-greet #child>
</app-greet>
<button (click)="child.greetMe()">
   Greet Me
</button>

With template reference variable #child, we can invoke methods present in greet.component.ts. On click of the button, greetMe() method is called, which display text “Hola User!”

Run below command to see the output:

ng serve -o

Live demo: