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.
Template reference variables in 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.
<input #myInput type="text"> <button (click)="alert(myInput.value)">Show Value</button>
<child-component #childRef></child-component>
<button (click)="childRef.doSomething()">Call Child Method</button><input #inputRef type="text"> <button (click)="inputRef.focus()">Focus Input</button>
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.
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}!`; } }
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.
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.