bhylu.com

Advertisements

Angular Template Reference Variables

A template reference names an element, component or exported directive inside its template scope. It does not create a global browser variable or a permanent application-state store.

How it works

A small desk note can read a native input through a local reference when the learner confirms it. The reference is passed as a value to a clear component operation. For more involved editing, a reactive form or a signal-backed model makes validation and state transitions easier to test. References inside a conditional or repeated view belong to that view’s scope.

Run the code

Use a separate empty project folder with a compatible Node version: ^22.22.3, ^24.15.0 or a supported 26+ runtime. The review uses Node 24.22.1, Angular 22.2.4, CLI/build 22.2.5 and TypeScript 6.0.3. Node 22.15.1 is too old for Angular 22. Save every download at its displayed path; browsers may keep only the basename, so recreate the src folder. Run npm install, npm run build and npm start, then open the loopback address printed by the server. Run npm test for the supplied component tests. These are local teaching projects, not Bhylu publishing files.

The small loopback server serves the compiled app and fixed, read-only tool API fixtures. It is not a database, authentication or lending service. Angular examples do not run in Bhylu’s current HTML or TypeScript playground. No Apache, MySQL or PHP configuration change is needed.

Example

src/app.ts

import { Component } from '@angular/core';
import { signal } from '@angular/core';

@Component({
  selector: 'bh-reference-variables',
  standalone: true,
  imports: [],
  template: `<label>Desk note<input #note /></label
    ><button type="button" (click)="save(note.value)">Preview note</button>
    <p data-result>{{ message() }}</p>`,
})
export class App {
  message = signal('No preview');
  save(value: string): void {
    this.message.set(value.trim() || 'No preview');
  }
}

Expected result

No preview

The test fills the input and confirms it, producing Return by five. The text is a local preview, not a saved loan record. The input reference is convenient for this small operation but should not become an excuse to bypass a form’s validation state.

Advertisements