Angular Component Interaction Using Template Reference Variables

Angular Component Interaction Using Template Reference Variables
Template Reference Variables


In this blog we learn how to parent component can directly access properties and methods of the child component using Template Reference Variables.

Basic understanding of Template variables:
Template variables help you use data from one part of a template in another part of the template. Use template variables to perform tasks such as respond to user input or finely tune your application's forms. You use the hash symbol '#' to declare a template variable.

Syntax:
<input #name placeholder="name" />

The following template variable, #name, declares a name variable on an <input> element.

Example:
app.component.ts
import { Component } from '@angular/core';

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

export class AppComponent{
	
}

app.component.html
<h1>Angular Component Interaction</h1>
<h2>Template Reference Variables</h2>

<h3>My name is {{child.name}}</h3>
<button (click)="child.alertMyName()">Alert My Name</button>
<app-child #child></app-child>

child.component.ts
import { Component } from '@angular/core';

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

export class ChildComponent{

  name: string = "Bhavesh";

  alertMyName(){
    alert("Hello bhavesh");
  }

}

In the above example, we have used the property and methods of the child component in the parent component using the template reference variable. by using a template reference variable you are able to access a child component properties and methods in the parent component template.

This feature is very useful when you working with nested components and forms.

Reference:

Comments