Template references let you easily get a part of your webpage in your code. This helps you change or read that part directly.
0
0
Template reference for direct access in Angular
Introduction
You want to get the value of an input box without using extra code.
You want to call a method on a child component from the template.
You want to focus an input box when a button is clicked.
You want to show or hide an element based on some condition using direct access.
Syntax
Angular
<element #refName></element>
The #refName creates a name you can use inside the template.
You can use this name to get the element or component directly in your template expressions.
Examples
This example uses a template reference
#myInput to focus the input box when the button is clicked.Angular
<input #myInput type="text"> <button (click)="myInput.focus()">Focus Input</button>
Here,
#childRef references a child component to call its method directly from the template.Angular
<child-component #childRef></child-component>
<button (click)="childRef.someMethod()">Call Child Method</button>This shows how to display the current value of an input box using its template reference.
Angular
<input #userName type="text">
<p>You typed: {{ userName.value }}</p>Sample Program
This component uses a template reference #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: ` <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 references only work inside the template where they are declared.
You cannot use template references to access elements or components in your TypeScript code directly; for that, use @ViewChild.
Summary
Template references let you name and access elements or components directly in your template.
They are useful for simple interactions like focusing inputs or reading values.
They keep your code clean by avoiding extra variables or event handlers.