0
0
Angularframework~5 mins

Template reference variables in Angular

Choose your learning style9 modes available
Introduction

Template reference variables let you easily access elements or components inside your Angular template. They help you interact with parts of your page without extra code.

You want to get the value of an input box when a button is clicked.
You need to call a method on a child component from the template.
You want to focus an input field programmatically.
You want to read or change properties of an HTML element directly in the template.
Syntax
Angular
<element #variableName></element>

The #variableName creates a reference to the element or component.

You can use this variable elsewhere in the template to access the element or component's properties and methods.

Examples
This example shows how to get the value of an input box when the button is clicked.
Angular
<input #myInput type="text">
<button (click)="alert(myInput.value)">Show Value</button>
Here, the template reference variable accesses a child component to call its method.
Angular
<child-component #childRef></child-component>
<button (click)="childRef.doSomething()">Call Child Method</button>
This example uses the reference to focus the input field when the button is clicked.
Angular
<input #inputRef type="text">
<button (click)="inputRef.focus()">Focus Input</button>
Sample Program

This component uses a template reference variable #nameInput to get the input value when the button is clicked. It then shows a greeting message below.

Angular
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>Template Reference Variable Demo</h1>
    <input #nameInput type="text" placeholder="Enter your name">
    <button (click)="greet(nameInput.value)">Greet</button>
    <p>{{ message }}</p>
  `
})
export class AppComponent {
  message = '';

  greet(name: string) {
    this.message = `Hello, ${name}!`;
  }
}
OutputSuccess
Important Notes

Template reference variables only work inside the template where they are declared.

They do not create variables in the component class, only in the template.

You can reference native HTML elements or Angular components.

Summary

Template reference variables let you access elements or components directly in your template.

They are useful for reading values, calling methods, or manipulating elements without extra code in the component.

Use #variableName syntax to create them and then use the variable in your template expressions.