Sometimes you only need to read the note box when the Send button is pressed. Adding a new property to the class and setting up [(ngModel)] only for that feels like too much.
A template reference variable (a variable in the template that points at an element) is enough for a small job like this. A template reference variable is a name you stick on an element in the template with a # sign. With that name, other parts of the template can point right at that element. <input #noteInput /> makes a name noteInput that holds the input box itself. Picture the jars on Jali's counter. You stick a "note" label on one of them. From then on anyone can just say "take what's in the jar labelled note", without copying its contents into a book first. In Angular, the jar is an element in the template, the label is #noteInput, and the book is a property in the class. The label only points at the element; it's not a copy of what's inside.
#name: a label for an element
This component sticks the label #noteInput on the note box:
import { Component } from '@angular/core'
@Component({
selector: 'app-order',
standalone: true,
template: `
<input #noteInput placeholder="Note" />
<button (click)="send(noteInput.value)">Send</button>
<button (click)="noteInput.value = ''; noteInput.focus()">Clear</button>
<p>Sent: {{ sent }}</p>
`,
})
export class Order {
sent = ''
send(text: string) {
this.sent = text
}
}
The box, the property and the page at each step:
| Event | In the box | sent |
Shows |
|---|---|---|---|
| The page first shows | (empty) | '' |
Sent: |
| Type "no spring onions" | no spring onions | '' |
Sent: |
| Click Send | no spring onions | 'no spring onions' |
Sent: no spring onions |
| Click Clear | (empty, cursor in the box) | 'no spring onions' |
Sent: no spring onions |
#noteInputmakes a variable you can use anywhere in this template. It holds the<input>element itself (anHTMLInputElement). So.value(what's in the box),.focus()(puts the cursor in the box) and every other DOM property are ready to use.send(noteInput.value)reads the box's content when the button is clicked, then hands it to the methodsend. While you type, the class receives nothing:sentstays''.- The Clear button runs two statements separated by a semicolon: it empties the box, then puts the cursor in it.
- This needs no
FormsModuleand no extra property. It suits "read what's in it when a button is pressed".
The exercise uses the same shape: <input #nameInput type="text" placeholder="Type a name" />, a button <button (click)="greet(nameInput.value)">Greet</button>, and <p>{{ message }}</p>. When you type Budi and press Greet, the starter's greet method fills message, and the paragraph reads Hello, Budi!.
A pointer, not a binding
Before you read on, take a guess. The template gets <p>Live: {{ noteInput.value }}</p>, and the box has no event binding at all. When you type "no spring onions", does the Live paragraph change letter by letter?
The answer is no. {{ noteInput.value }} is read again only when Angular checks the template. Angular checks the template after an event it listens to, such as the (click) on the Send button. A box with no event binding tells Angular nothing when you type in it.
So the Live paragraph does not change while you type. It only catches up when you click Send or Clear. If you want it to follow every letter, give the box an event binding, even one that does nothing:
<input #noteInput (input)="0" placeholder="Note" />
<p>Live: {{ noteInput.value }}</p>
(input)="0" only makes Angular listen to typing: its content, 0, does nothing. Each keystroke then triggers a template check. If the box's content really needs to live in the class, [(ngModel)] from the Two-Way Binding lesson fits better.
# on a component: pointing at its instance
On a component's tag, # points at the component class's instance, not at the HTML element. Say Order also has count = 0 and an increment() method, as in the Angular Event Binding lesson:
<!-- App's template, with Order in imports -->
<app-order #order />
<button (click)="order.increment()">Add from App</button>
<p>App reads: {{ order.count }}</p>
Two clicks on App's button give Count: 2 inside Order and App reads: 2 in App. App calls its child component's method and reads its property directly, with no input or output. Some directives can be pointed at by their export name too (the name the directive offers for #). For example, #model="ngModel" makes model hold the NgModel object, with model.valid (whether the value passes the rules) and model.dirty (whether the user has changed it).
@ViewChild: a label the class reads
A # variable can only be used in the template. To use it from the class, fetch it with the @ViewChild decorator:
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core'
export class Order implements AfterViewInit {
@ViewChild('noteInput') noteInput!: ElementRef<HTMLInputElement>
ngAfterViewInit() {
this.noteInput.nativeElement.focus()
}
}
@ViewChild('noteInput')looks for the element labelled#noteInputin this component's template. The result is anElementRef(a wrapper around the element), and the real element is in.nativeElement. The!means Angular fills the value in later, so it needs no starting value.- The element only exists after the template is shown.
ngAfterViewInitis a method Angular calls once, right after that, andimplements AfterViewInitmakes sure the class has that method. The details are in the Lifecycle Hooks lesson.
The constructor and ngOnInit are also called automatically, but earlier: when the component is created, before the template is shown. What this.noteInput holds in each place:
| Read in | What this.noteInput holds in Angular 18 |
|---|---|
constructor |
undefined |
ngOnInit |
undefined |
ngAfterViewInit |
an ElementRef holding the <input> |
ngOnInit with @ViewChild('noteInput', { static: true }) |
an ElementRef holding the <input> |
{ static: true } is fine when the element is always there, not inside @if or @for. Angular CLI projects also have a signal form, noteInput = viewChild<ElementRef<HTMLInputElement>>('noteInput'), read as this.noteInput(). The exercise editor and the Playground don't recognise it yet, so it comes back undefined.
⚠️ Why is it undefined?
- Forgetting the
#or mistyping the name.<input nameInput>ornameInpt.valuehas no matching label. When the button is clicked, the console writesERROR Cannot read properties of undefined (reading 'value'), and the paragraph stays empty. - A label inside
@ifused outside it. A#variable is only visible in the block where it's made. From outside the block the result is the same:Cannot read properties of undefined (reading 'value'). - Reading
@ViewChildtoo early. In theconstructorandngOnInitit'sundefined. UsengAfterViewInit, or{ static: true }. - The exercise's details. The grader types
Budi, presses the button whose text is exactlyGreet, then reads the first<p>. Show the greeting in that paragraph, not throughalert, and put no other paragraph above it.
TL;DR: A template reference variable is a label you stick on an element with #, for example #noteInput on an input box. Anywhere in that template, noteInput holds the real element. So send(noteInput.value) reads the box's content when the button is clicked, without FormsModule. The label is a pointer, not a binding: {{ noteInput.value }} only updates after an event Angular listens to, or on every keystroke if the box gets (input)="0". On a component's tag, #order holds that component's class instance, so order.increment() can be called directly. From the class, @ViewChild('noteInput') fetches the labelled element as an ElementRef (a wrapper around the element). It's only filled in ngAfterViewInit, a method that runs after the template shows, or earlier, in ngOnInit, with { static: true }.
⚡ # sticks a label on an element
Write:
<input #noteInput placeholder="Note" />
<button (click)="send(noteInput.value)">Send</button>
Meaning: #noteInput is a template reference variable: a label that points at this element. noteInput holds the real <input> element, so .value (what's in the box) is read when the button is clicked, then handed to the method send. No FormsModule or extra property needed.
In the exercise, the grader types Budi, presses the button whose text is exactly Greet, then reads the first <p>.
⚡ A pointer, not a binding
Write:
<input #noteInput (input)="0" placeholder="Note" />
<p>Live: {{ noteInput.value }}</p>
Guess first: without (input)="0", does the Live paragraph change with every letter you type?
No. {{ noteInput.value }} is read again only after an event Angular listens to. A box with no event binding tells Angular nothing when you type in it.
Meaning: A # label is only a pointer, not a binding, so Angular doesn't update the Live paragraph by itself. (input)="0" is an event binding whose content does nothing. It only makes Angular listen to typing, so every letter makes Angular check the template again, and the Live paragraph changes too.
⚡ @ViewChild: the class reads the label
Write:
@ViewChild('noteInput') noteInput!: ElementRef<HTMLInputElement>
ngAfterViewInit() {
this.noteInput.nativeElement.focus()
}
Meaning: @ViewChild('noteInput') fetches the element labelled #noteInput so the class can use it. The result is a wrapper around the element (ElementRef), and the real element is in .nativeElement. That element only exists after the template is shown, so in the constructor and ngOnInit, which run earlier, it's undefined. Use ngAfterViewInit (a method Angular calls right after the template shows), or add { static: true } to @ViewChild when the element is always there.