Angular Template Reference Variables (#var)

Master Angular Template Reference Variables with practical examples, forms, ViewChild integration, component references, DOM access, Angular 17+ examples, Mermaid diagrams, and interview questions.

Template Reference Variables are one of Angular's simplest yet most powerful features. They allow developers to reference HTML elements, Angular directives, components, or template instances directly within an Angular template.

Instead of writing additional TypeScript code for simple interactions, Template Reference Variables provide a clean and efficient way to interact with the template.

They are frequently used with:

  • Forms
  • ViewChild
  • Child Components
  • Input Elements
  • Template Directives
  • Angular Material Components

This is a commonly asked topic in Angular interviews because it demonstrates understanding of Angular templates and component interaction.


Table of Contents

  • What are Template Reference Variables?
  • Why Use Them?
  • Syntax
  • DOM Element References
  • Component References
  • Form References
  • ng-template References
  • ViewChild Integration
  • Angular 17+ Usage
  • Best Practices
  • Top 10 Interview Questions
  • Summary

What are Template Reference Variables?

A Template Reference Variable is a variable declared inside an Angular template using the # symbol.

Example:

<input #searchBox>

The variable searchBox refers to the input element and can be accessed anywhere within the same template.


Why Use Template Reference Variables?

They simplify common UI interactions such as:

  • Reading input values
  • Setting focus
  • Calling component methods
  • Accessing form state
  • Working with templates
  • Integrating with ViewChild

Template Reference Variable Architecture

flowchart LR

Template

Template --> InputElement

InputElement --> TemplateReference

TemplateReference --> ButtonClick

ButtonClick --> DOMInteraction

Basic Syntax

<input #username>

<button>

Submit

</button>

Here:

#username

creates a reference to the input element.


Accessing Input Values

<input #name>

<button
(click)="show(name.value)">

Show

</button>
show(value:string){

console.log(value);

}

Output

Angular

Flow of Input Value

sequenceDiagram

participant User

participant Input

participant TemplateVariable

participant Component

User->>Input: Enter Text

Input->>TemplateVariable: Store Reference

TemplateVariable->>Component: Pass Value

Component-->>User: Display Result

Setting Focus

<input #email>

<button

(click)="email.focus()">

Focus

</button>

Angular automatically exposes the native DOM API for the referenced element.


Referencing Components

Template Reference Variables can point to child components.

Child Component

@Component({
  selector:'app-user',
  standalone:true,
  template:`
     <h2>User Component</h2>
  `
})
export class UserComponent{

    refresh(){

       console.log("Refreshing");

    }

}

Parent Template

<app-user

#user>

</app-user>

<button

(click)="user.refresh()">

Refresh

</button>

Component Reference Flow

flowchart LR

ParentTemplate

ParentTemplate --> ChildComponent

ChildComponent --> TemplateReference

TemplateReference --> CallMethod

Using Template Reference with Forms

<form #loginForm="ngForm">

<input

name="email"

ngModel>

<button>

Login

</button>

</form>

Angular associates the template reference with the NgForm directive.


Accessing Form State

<form #form="ngForm">

<input

name="email"

required

ngModel>

</form>

<p>

{{form.valid}}

</p>

Output

true

or

false

Template Reference with ng-template

<ng-template #loading>

Loading...

</ng-template>

Later it can be rendered using:

<ng-container

*ngTemplateOutlet="loading">

</ng-container>

ng-template Architecture

flowchart TD

ng-template

ng-template --> TemplateReference

TemplateReference --> ngTemplateOutlet

ngTemplateOutlet --> Browser

Using ViewChild with Template References

Template references can be accessed in TypeScript.

<input #search>
@ViewChild("search")

search!:ElementRef<HTMLInputElement>;

ngAfterViewInit(){

this.search.nativeElement.focus();

}

ViewChild Integration

flowchart TD

TemplateReference

TemplateReference --> ViewChild

ViewChild --> Component

Component --> DOM

Reading Directive Instances

A template reference can point to a directive instead of an element.

<form #login="ngForm">

</form>

Here

login

references the NgForm directive.


Local Scope

Template Reference Variables are only available inside the template where they are declared.

<div>

<input #username>

</div>

The variable cannot be accessed from another component template.


Angular Material Example

<mat-menu #menu="matMenu">

<button mat-menu-item>

Home

</button>

</mat-menu>

<button

[matMenuTriggerFor]="menu">

Menu

</button>

Template variables are heavily used throughout Angular Material.


Angular 17+ Example

<input #search>

@if(search.value){

<p>

Searching for:

{{search.value}}

</p>

}

Template Reference Variables work seamlessly with Angular's new control flow syntax.


Real-World Banking Example

flowchart TD

LoginPage

LoginPage --> UsernameInput

UsernameInput --> TemplateVariable

TemplateVariable --> LoginButton

LoginButton --> Authenticate

Authenticate --> Dashboard

Example

<input #accountNumber>

<button

(click)="search(accountNumber.value)">

Search

</button>

The account number is passed directly without creating additional component properties.


Template Reference Variable vs ViewChild

Template Reference ViewChild
Template Only TypeScript
Simple interactions Complex logic
No lifecycle needed Available after lifecycle hook
Lightweight More powerful
Local Scope Component Scope

Common Use Cases

Requirement Solution
Read Input Value Template Variable
Focus Input Template Variable
Access Form #form="ngForm"
Child Component #child
ViewChild @ViewChild()
ng-template #template
Angular Material Menu/Dialog References

Best Practices

  • Use Template Reference Variables for simple template interactions.
  • Use @ViewChild() when TypeScript access is required.
  • Keep variable names meaningful.
  • Avoid excessive template logic.
  • Prefer template references over unnecessary component properties.
  • Use them with Angular forms for cleaner code.

Common Mistakes

  • Trying to access a template variable outside its template.
  • Confusing Template Reference Variables with component variables.
  • Using ViewChild when template access alone is sufficient.
  • Giving multiple elements the same reference name in the same scope.
  • Performing complex business logic directly in the template.

Advantages

Feature Benefit
Simple Syntax Easy to learn
Lightweight Minimal code
DOM Access Direct interaction
Forms Easy validation
Components Call child methods
Angular Material Works naturally
ViewChild Seamless integration

Top 10 Angular Template Reference Variable Interview Questions

1. What is a Template Reference Variable?

Answer

A Template Reference Variable is a local variable created using the # symbol. It provides a reference to an HTML element, Angular directive, or component within the same template.


2. How do you create a Template Reference Variable?

Answer

<input #username>

The variable username now references the input element.


3. Can Template Reference Variables access component methods?

Answer

Yes. When the reference points to a child component, its public methods and properties can be accessed directly.

Example:

<app-user #user></app-user>

<button (click)="user.refresh()">
  Refresh
</button>

4. What is the difference between a Template Reference Variable and @ViewChild()?

Template Reference @ViewChild()
Used in HTML templates Used in TypeScript
No lifecycle dependency Available after lifecycle hooks
Ideal for simple interactions Suitable for advanced component logic

5. Can Template Reference Variables be used with Angular Forms?

Answer

Yes. They are commonly used with template-driven forms.

Example:

<form #loginForm="ngForm">

This references the NgForm directive.


6. What is the scope of a Template Reference Variable?

Answer

Its scope is limited to the template where it is declared. It cannot be accessed from another component or template.


7. Can a Template Reference Variable reference a directive?

Answer

Yes. By assigning an export alias, it can reference Angular directives such as NgForm, MatMenu, or custom directives.


8. Can Template Reference Variables work with Angular 17 control flow?

Answer

Yes. They work with the new @if, @for, and @switch syntax just as they do with traditional structural directives.


9. When should you use a Template Reference Variable instead of a component property?

Answer

Use a Template Reference Variable for simple UI interactions such as reading an input value or focusing an element. Use component properties when the value needs to participate in application logic or state management.


10. What are the advantages of Template Reference Variables?

Answer

  • Less TypeScript code
  • Cleaner templates
  • Easy DOM access
  • Works well with forms
  • Simple child component interaction
  • Integrates with @ViewChild()
  • Improves readability for straightforward UI tasks

Interview Cheat Sheet

Topic Remember
Syntax #variable
DOM Element #input
Component Reference #child
Form Reference #form="ngForm"
Template Reference #loading
Access TypeScript @ViewChild()
Scope Local Template
Angular Material Common Usage
Angular 17+ Works with @if
Best Use Simple UI Interaction

Summary

Template Reference Variables provide a simple, lightweight mechanism for interacting with HTML elements, Angular directives, child components, and templates directly from Angular templates. They reduce unnecessary TypeScript code for straightforward UI tasks and integrate seamlessly with forms, Angular Material, @ViewChild(), and modern Angular control flow. Knowing when to use Template Reference Variables versus @ViewChild() is an important skill for building clean, maintainable Angular applications and performing well in Angular interviews.


Next Article

➡️ 17-Angular-Data-Binding-QA.md