Sub topic 6
Reading Elements with Template Reference Variables
This chapter assumes you know event binding and interpolation from the previous chapters. It also assumes you are comfortable with the HTMLInputElement DOM type.
Sometimes a template needs a value straight from an element, such as the text in an input when a button is clicked. You could store that text in a component field with an event binding. Often a direct reference is simpler. A template reference variable gives a name to an element, component, or directive inside the template. You declare one with #.
Declaring and Using a Reference
Put #name on an element. Any expression in the same template can then use name. On a plain HTML element, the variable holds the DOM element itself.
import { Component } from '@angular/core';
@Component({
selector: 'app-todo-entry',
template: `
<input #task placeholder="New task" (keyup.enter)="add(task)">
<button (click)="add(task)">Add</button>
<ul>
@for (item of items; track $index) {
<li>{{ item }}</li>
}
</ul>
`,
})
export class TodoEntryComponent {
items: string[] = [];
add(input: HTMLInputElement) {
const text = input.value.trim();
if (text) {
this.items.push(text);
input.value = '';
}
}
}The button and the Enter key both pass the input element to add(). The method reads the text, saves it, and clears the box. No component field has to track each keystroke. You can also pass only the value, as in add(task.value), when the method doesn't need the element.
What the Variable Points To
The value Angular assigns depends on where you put the #.
| Declaration | Resolves to | Example use |
|---|---|---|
| `<input #box>` | `HTMLInputElement` | `box.value`, `box.focus()` |
| `<app-timer #timer />` | `TimerComponent` instance | `timer.reset()` |
| `<form #f="ngForm">` | `NgForm` directive | `f.valid` |
A component reference lets the parent call public methods on the child directly from the template:
import { Component } from '@angular/core';
@Component({
selector: 'app-timer',
template: `<p>{{ seconds }}s</p>`,
})
export class TimerComponent {
seconds = 42;
reset() {
this.seconds = 0;
}
}
@Component({
selector: 'app-root',
imports: [TimerComponent],
template: `
<app-timer #timer />
<button (click)="timer.reset()">Reset timer</button>
`,
})
export class AppComponent {}Common Errors
Expecting the display to update on its own
{{ box.value }} reads the element's current value only when change detection runs. Typing into an input that has no event binding may not trigger change detection, so the text on screen goes stale. Add an event binding such as (input), or move the value into component state.
Crossing a block boundary
A reference declared inside @if, @for, or an <ng-template> exists only in that block. Code inside a block can see references declared outside it, but code outside cannot see references declared inside.
Using the reference in the class
Template variables exist only in the template. To reach an element from TypeScript, use viewChild() or @ViewChild, or pass the reference as a method argument as shown above.
Shadowing component members
If a reference has the same name as a component property, the template uses the reference. Choose names that don't collide.
Exercise
A template contains <input #city> and <p>{{ city.value }}</p>, and has no other bindings. When the user types, the paragraph stays empty. Why, and what is the smallest fix?
Show answer
Typing does not fire any event Angular is listening for, so change detection never runs again and the interpolation keeps its first, empty value. Add an event binding, for example <input #city (input)="0">. Each keystroke then triggers change detection and the paragraph updates. A cleaner fix is to store the value in component state.
Exercise
Inside @if (show) { <input #email> }, a button placed after the @if block uses (click)="send(email.value)". What goes wrong?
Show answer
The reference email is scoped to the @if block, so the button outside the block cannot see it and the template fails to compile. Move the button inside the block, or keep the email in component state.