Sub topic 6
Reading Elements with Template Reference Variables
Sometimes you only need a value for a moment. A typical case is the text in a search box at the instant the user presses Enter, and keeping that text in a component field would be unnecessary work. Template reference variables cover this case. They give a name, inside the template, to an element, a component, or a directive, so other parts of the same template can read from it or call methods on it.
This chapter assumes you know event binding and $event from the previous chapter. It also assumes you can read basic DOM properties such as HTMLInputElement.value and have used @if and @for control flow blocks.
Declaring a Template Reference Variable
You declare a template reference variable by adding #name to an element. Any binding or statement in the same template can then use name.
import { Component } from '@angular/core';
@Component({
selector: 'app-todo-entry',
template: `
<input #box placeholder="New task" (keyup.enter)="add(box)">
<button (click)="add(box)">Add</button>
<ul>
@for (task of tasks; track $index) {
<li>{{ task }}</li>
}
</ul>
`,
})
export class TodoEntryComponent {
tasks: string[] = [];
add(input: HTMLInputElement) {
const text = input.value.trim();
if (text) {
this.tasks.push(text);
}
input.value = '';
input.focus();
}
}Here box is the actual HTMLInputElement that the browser created. The component class has no field holding the draft text. Angular passes the element to add() only when the user presses Enter or clicks the button, and the method reads value, clears it, and puts focus back on the field.
Compare this with the $event approach from the event binding chapter. With $event you can only reach the element that fired the event. The button's click event has event.target set to the button, not the input. A reference variable lets one element's event handler read a different element directly.
What the Variable Refers To
The value of #name depends on where you put it. Angular resolves the variable with these rules:
| Placement | Example | Variable holds |
|---|---|---|
| Plain HTML element | `<input #box>` | `HTMLInputElement` |
| Component selector | `<app-counter #c />` | The `CounterComponent` instance |
| `ng-template` | `<ng-template #tpl>` | `TemplateRef<unknown>` |
| With an `exportAs` name | `<form #f="ngForm">` | The `NgForm` directive instance |
Referencing a child component
When the variable sits on a component's host element, you get the component instance itself. This means the template can call the child's public methods and read its public fields or signals. The following example reuses the signal-based counter idea from the tutorial plan:
import { Component, model } from '@angular/core';
@Component({
selector: 'app-counter',
template: `<p>Count: {{ count() }}</p>`,
})
export class CounterComponent {
count = model(0);
increment() {
this.count.update(c => c + 1);
}
clear() {
this.count.set(0);
}
}
@Component({
selector: 'app-root',
imports: [CounterComponent],
template: `
<app-counter #counter />
<button (click)="counter.increment()">+1</button>
<button (click)="counter.clear()">Clear</button>
<p>Parent reads: {{ counter.count() }}</p>
`,
})
export class AppComponent {}The parent component class contains no code. The template does all the wiring. This works well for small, local control. However, the parent now depends on the child's method names. That is tighter coupling than inputs and outputs, which later chapters cover. Use inputs and outputs when the relationship is part of a component's public contract, and keep reference variables for quick local control.
Referencing a directive with exportAs
A directive can publish itself under a name through the exportAs option in its metadata. NgForm exports as ngForm, and NgModel exports as ngModel. Assigning that name to the variable gives you the directive instead of the element:
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [FormsModule],
template: `
<form #signup="ngForm" (ngSubmit)="submit(signup)">
<input name="email" ngModel required email #email="ngModel">
@if (email.invalid && email.touched) {
<p>Enter a valid email address.</p>
}
<button [disabled]="signup.invalid">Sign up</button>
</form>
`,
})
export class SignupComponent {
submit(form: NgForm) {
console.log(form.value);
}
}#email without a value would hold the <input> element, and that element has no invalid or touched property. Writing #email="ngModel" gives you the NgModel directive, which tracks validation state. The next chapters cover ngModel and two-way binding in more detail.
Scope Rules
A template reference variable is visible throughout the template where it is declared, including in elements that come before it in the markup. Structural boundaries limit that visibility. @if, @for, @switch, @defer blocks, ng-template, and the older *ngIf and *ngFor each create a nested template. Inner templates can see outer variables, but outer templates cannot see inner ones.
import { Component } from '@angular/core';
@Component({
selector: 'app-scope-demo',
template: `
<input #outer (input)="0">
<button (click)="show = !show">Toggle</button>
@if (show) {
<input #inner (input)="0">
<p>Outer from inside: {{ outer.value }}</p>
}
<!-- {{ inner.value }} here would fail to compile: inner is out of scope -->
`,
})
export class ScopeDemoComponent {
show = true;
}Inside a @for block, each repetition gets its own copy of the variable. #row inside a loop refers to that row's element only. From outside the loop there is no single row to point to, so you cannot use it there.
When you need to reach elements inside a block from outside, or from the component class, use a view query (viewChild or viewChildren). A view query is kept up to date as blocks appear and disappear.
Name collisions
If a reference variable has the same name as a component property, the template variable wins inside the template. Writing #name on an input in a component that also has a name field will quietly hide the field. Choose names that make clear they point to an element, such as nameInput or searchBox.
The Stale Interpolation Gotcha
Reading a reference variable inside interpolation looks reactive, but it is not:
import { Component } from '@angular/core';
@Component({
selector: 'app-mirror',
template: `
<input #box>
<p>Broken mirror: {{ box.value }}</p>
<input #box2 (input)="0">
<p>Working mirror: {{ box2.value }}</p>
`,
})
export class MirrorComponent {}The first paragraph stays empty while you type. Angular re-evaluates bindings only when change detection runs for the view. Typing into a plain input changes the DOM's value but does not notify Angular, so nothing causes the view to be checked again. The second input has an event binding. Any template event listener marks the view for checking, in both zone-based and zoneless apps. The statement 0 does nothing, but the listener being there is what causes the refresh.
The (input)="0" trick is fine for demos. In real code, if a value is meant to drive the display, store it in state: a field updated from the event, a signal, or ngModel. The change detection chapter explains when views are checked.
Reaching References from the Class
The class cannot see template variables directly. To get one in TypeScript, query it by name with viewChild:
import { Component, ElementRef, afterNextRender, viewChild } from '@angular/core';
@Component({
selector: 'app-search',
template: `<input #searchBox placeholder="Search">`,
})
export class SearchComponent {
searchBox = viewChild.required<ElementRef<HTMLInputElement>>('searchBox');
constructor() {
afterNextRender(() => this.searchBox().nativeElement.focus());
}
}A view query on a plain element returns an ElementRef, and the real node is in its nativeElement property. This differs from the template, where #searchBox gives you the element itself. Direct DOM access does not work under server-side rendering, which is why the example waits for afterNextRender, a hook that runs only in the browser after rendering.
Choosing an Approach
| Need | Use |
|---|---|
| Read a value at the moment of an action | Template reference variable |
| Read the element that fired the event | `$event.target` |
| Show the value continuously as it changes | Component field or signal, or `ngModel` |
| Show form validation state in the template | `#x="ngModel"` or `#f="ngForm"` |
| Use the element or child component in class code | `viewChild` / `viewChildren` |
| Long-term parent-child contract | Inputs and outputs |
Exercise
A template contains <input #query> followed by <p>{{ query.value.length }} characters</p>. The count stays at 0 while the user types. Explain why, and give two fixes: one minimal and one that is better for production code.
Show answer
Typing changes the DOM value but triggers no Angular event listener, so change detection does not re-check the view and the interpolation is never re-evaluated. Minimal fix: add an event binding such as (input)="0" to the input, so each keystroke marks the view for checking. Better fix: keep the text in state, for example text = signal('') with (input)="text.set($any($event.target).value)" and {{ text().length }}, or use [(ngModel)].
Exercise
You place <li #item> inside an @for block and try to write (click)="item.scrollIntoView()" on a button below the loop. What happens, and how should you get a specific list item instead?
Show answer
It fails to compile because item is declared inside the @for block's nested template and is not visible in the outer template. Each repetition has its own item. Either put the button inside the loop so it uses that row's item, or query all rows from the class with viewChildren('item') and choose one by index.
Exercise
What does #ctrl hold in <input name="age" ngModel #ctrl> compared with <input name="age" ngModel #ctrl="ngModel">, and which one lets you write ctrl.errors?
Show answer
Without a value, ctrl is the native HTMLInputElement. With ="ngModel", it is the NgModel directive instance, found through its exportAs name. Only the NgModel directive has errors, valid, touched, and similar control-state properties, so ctrl.errors works only in the second form.