Sub topic 13
Template Reference Variables
This chapter assumes you already know interpolation, property binding, event binding, and @if/@for control flow from earlier chapters. It also assumes you can write a standalone component with signals. Template reference variables let one part of a template point at another part, such as an element, a child component, or a directive, without writing any code in the component class.
The Working Model
A template reference variable is a name you declare on an element with the # prefix. Angular binds that name to something on that element, and any expression elsewhere in the same template can read it.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-greeter',
template: `
<input #nameBox placeholder="Your name" />
<button (click)="greet(nameBox.value); nameBox.value = ''">Greet</button>
<p>{{ greeting() }}</p>
`
})
export class GreeterComponent {
greeting = signal('');
greet(name: string) {
this.greeting.set(name ? `Hello, ${name}!` : 'Type a name first.');
}
}In this example, nameBox holds the real HTMLInputElement. The click handler reads its value, hands the string to the class, and then clears the field. The class never sees the element. It only receives the value it needs, and that keeps the class simple and easy to test.
What the Variable Refers To
The value of the variable depends on where you put it.
| Declared on | Example | Variable holds |
|---|---|---|
| A plain DOM element | `<input #box>` | The native element (`HTMLInputElement`) |
| A component's host element | `<app-stopwatch #sw>` | The component instance |
| An element with `#name="exportName"` | `<div appDisclosure #d="disclosure">` | The directive instance exported under that name |
| An `<ng-template>` | `<ng-template #tpl>` | A `TemplateRef` |
Referencing a Child Component
When the variable sits on a component's tag, it gives you the component instance. You can then call the child's public methods and read its signals right from the parent template.
import { Component, signal, OnDestroy } from '@angular/core';
@Component({
selector: 'app-stopwatch',
template: `<span>{{ seconds() }}s</span>`
})
export class StopwatchComponent implements OnDestroy {
seconds = signal(0);
private handle: ReturnType<typeof setInterval> | undefined;
start() {
if (this.handle) return;
this.handle = setInterval(() => this.seconds.update(s => s + 1), 1000);
}
stop() {
clearInterval(this.handle);
this.handle = undefined;
}
reset() {
this.stop();
this.seconds.set(0);
}
ngOnDestroy() {
this.stop();
}
}
@Component({
selector: 'app-race',
imports: [StopwatchComponent],
template: `
<app-stopwatch #sw />
<button (click)="sw.start()">Start</button>
<button (click)="sw.stop()">Stop</button>
<button (click)="sw.reset()">Reset</button>
@if (sw.seconds() >= 10) {
<p>Ten seconds passed.</p>
}
`
})
export class RaceComponent {}RaceComponent has no class code at all. Every interaction runs through sw. This works well when the parent drives the child only from its template. If the parent's class needs the child, for example to call reset() after an HTTP request, use a viewChild query instead. That is covered in the "Accessing Children with viewChild and contentChild" chapter.
Exporting Directives with exportAs
An element can host several directives, so a bare #ref on it can't tell which one you want. A directive (or component) declares a public name with exportAs, and the template asks for it with #ref="thatName".
import { Component, Directive, signal } from '@angular/core';
@Directive({
selector: '[appDisclosure]',
exportAs: 'disclosure'
})
export class DisclosureDirective {
open = signal(false);
toggle() {
this.open.update(v => !v);
}
}
@Component({
selector: 'app-faq',
imports: [DisclosureDirective],
template: `
<section appDisclosure #faq="disclosure">
<button (click)="faq.toggle()">
{{ faq.open() ? 'Hide' : 'Show' }} answer
</button>
@if (faq.open()) {
<p>Angular resolves the reference at compile time.</p>
}
</section>
`
})
export class FaqComponent {}Angular's own forms use this pattern: #f="ngForm" and #email="ngModel" give you the form and control objects. If no directive on the element exports the name you asked for, Angular throws error NG0301, "Export of name '...' not found". The usual cause is a missing entry in imports.
Scope Rules
A reference is visible throughout the template block where it is declared, including in nested blocks. It is also visible in sibling markup that appears before the declaration. It is not visible outside the block that contains it.
Every @if, @for, @switch case, @defer block, and <ng-template> creates its own scope:
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-tags',
template: `
<input #filter (input)="term.set(filter.value)" placeholder="Filter" />
@for (tag of tags; track tag) {
@if (tag.includes(term())) {
<label>
<input type="checkbox" #box />
{{ tag }}
<button (click)="box.checked = !box.checked">flip</button>
</label>
}
}
<button (click)="filter.value = ''; term.set('')">Clear filter</button>
`
})
export class TagsComponent {
tags = ['angular', 'signals', 'templates'];
term = signal('');
}Here filter is declared at the top level, so the last button can use it. Each @for iteration gets its own box, so each "flip" button toggles only its own checkbox. Using box after the loop would fail to compile, because no single box exists at that level.
Common Errors and Gotchas
Displaying an element's live state
Writing <input #q> {{ q.value }} looks reasonable, but the text won't update as you type. A DOM property changing is not something Angular tracks. The view refreshes only when change detection runs for this component, for example after a bound event handler fires or a signal it reads changes. Adding (input)="0" happens to work because the event binding marks the view for checking, but that's a hack. Copy the value into a signal from the event, as TagsComponent does with term, and display the signal.
Name shadowing
A reference with the same name as a class member hides that member inside the template. If the class has title and the template declares #title, then {{ title }} shows the element and not your string. Pick distinct names, such as titleInput.
Unavailable at class construction
A reference exists only inside the template. Class fields and the constructor can't see it. Even a viewChild query of it resolves only after the view is created, which is a lifecycle concern covered later.
Expecting a component, getting the element
#ref on a component's host tag gives you the component. If you need the host's DOM node, you have to query it with read: ElementRef. A template reference alone can't give you both.
Template-only typing
With strict templates on (the CLI default), the compiler knows each reference's type. nameBox.value type-checks as string, and a typo like sw.strat() is a build error, not a runtime surprise.
Choosing Between a Reference and the Alternatives
| Need | Use |
|---|---|
| Pass an element's current value to a handler once | Template reference |
| Call a child's method from a button in the template | Template reference |
| Show data that changes over time | A signal updated by an event |
| Access the element or child from class code | `viewChild` / `contentChild` |
| Name a computed value for reuse in the template | `@let` declaration |
Exercise
A template contains <app-player #p /> followed by @if (ready()) { <button (click)="p.play()">Play</button> }. A teammate moves <app-player #p /> inside the @if block and adds a second button after the block that also calls p.play(). What happens, and why?
Show answer
The build fails at the second button. Moving the declaration into the @if block scopes p to that block. The button inside the block still works, but the button after the block can't see p. Either move the player back to the top level, or put both buttons inside the block.
Exercise
Write the template markup that shows a character count under a textarea and updates the count as the user types, using a template reference variable to read the value and a signal named count in the class.
Show answer
<textarea #msg (input)="count.set(msg.value.length)"></textarea> <p>{{ count() }} characters</p> with count = signal(0); in the class. The reference reads the value inside the event handler, and the signal drives the display. Interpolating msg.value.length directly would not refresh reliably.
Exercise
You write <form appAutosave #s="autosave">, but the browser reports NG0301: Export of name 'autosave' not found. List two likely causes.
Show answer
First, AutosaveDirective is missing from the component's imports array, so no directive matches the element. Second, the directive's exportAs value is different from 'autosave', or it isn't set at all. A third possibility is that the directive's selector doesn't match appAutosave.