Angular Template Reference Variables

🎯 What Are Template Reference Variables in Angular?

A Template Reference Variable is a variable created in an Angular template (HTML) using #variableName.

It gives you direct access to an element, component, or directive inside the template.

Syntax:

#myVar

Why Do We Use Template Reference Variables?

You use them to:

✔ Access input field values
✔ Control DOM elements
✔ Call methods on child components
✔ Work with forms

They remove the need for TypeScript code in many simple cases.


📌 1️⃣ Example: Get Value from Input


TS


 

Here:

  • #box → reference to input element

  • box.value → gives current text inside input


📌 2️⃣ Using Template Variables with DOM Elements


Live update without TypeScript!


📌 3️⃣ Access Child Component Methods

If you have a child component:

child.component.ts


Use template reference to access it:

parent.component.html


 

#childRef gives access to the entire Child Component instance.


📌 4️⃣ With ngModel (Template-driven forms)


 

Here:

  • #email="ngModel" exposes ngModel API.


📌 5️⃣ Use with ViewChild Alternative (Template Only Solution)

Sometimes instead of writing:


You can simply use:


When you only need it in template.


⚠️ Important Notes

❗ Template reference variables work inside the same template only

You cannot access them from a different component template.

❗ They do not exist in TypeScript until passed as arguments.


Quick Summary

Feature What it does
#var Creates reference in template
Access DOM var.value, var.checked, etc.
Call component methods childRef.method()
Works with forms Can access validation, form state
Simplifies code No TS needed for simple tasks

🎉 Example You Can Try Immediately


 

You may also like...