AI Hints
Home›Angular Tutorial›host Listeners, Template Reference Variables and Practice: A Price List
Angular · Lesson 62 of 120

Template Reference Variables

Name an element.

⏱ 2 min read▶ Video at 1:13:02🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Sometimes a template needs to read an element directly. Like the text in a search box, when a button is clicked.

  • Read an element
  • The search box text
  • On a click

#name

A hash, and a name, on an element, creates a template reference variable. Anywhere in the same template, that name refers to the element. So box dot value reads the text in the input. No code in the class is needed.

keyvalue
<input #box>name the element
box.valueread it in the template
Scopethe same template
Class codenot needed

The input is named box. When the button is clicked, its value goes into the search signal. Matches is computed from search, and lists the titles that contain it. We type the letter o, and click search. Run it. Only The Hobbit, and Persuasion, contain an o.

app.tstypescript
import { Component, signal, computed } from '@angular/core';
import { BOOKS } from './books';

@Component({
  selector: 'app-root',
  template: `
    <input #box placeholder="Search titles">
    <button (click)="search.set(box.value)">Search</button>
    <p>Searching for: "{{ search() }}"</p>
    @for (b of matches(); track b.id) { <p>{{ b.title }}</p> }
  `,
})
export class App {
  search = signal('');
  matches = computed(() =>
    BOOKS.filter(b => b.title.toLowerCase().includes(this.search().toLowerCase())));
}
Also uses books.ts
export interface Book {
  id: number;
  title: string;
  author: string;
  price: number;
  stock: number;
}

export const BOOKS: Book[] = [
  { id: 1, title: 'Dune', author: 'Frank Herbert', price: 9.99, stock: 4 },
  { id: 2, title: 'The Hobbit', author: 'J.R.R. Tolkien', price: 8.99, stock: 0 },
  { id: 3, title: 'Circe', author: 'Madeline Miller', price: 10.99, stock: 2 },
  { id: 4, title: 'Emma', author: 'Jane Austen', price: 6.99, stock: 7 },
  { id: 5, title: 'Persuasion', author: 'Jane Austen', price: 7.49, stock: 1 },
];
Also uses actions.json
[{"type": "input", "text": "o"}, {"click": "button"}]

#ref or a signal?

A reference variable is great for reading a value once, like on a click. If the page must update with every key press, bind the input to a signal instead. Forms, in module ten, take this further.

#box

  • read when neededno class codesimple cases

signal + (input)

  • updates every keystate in the classlive behaviour

Summary

A hash, and a name, give an element a name, that the template can read. Next, some practice.

Key takeaways
  • <input #box>
  • box.value
  • Same template
Next up: Practice: A Price List — your turn