bhylu.com

Advertisements

Angular Null-Safe Navigation

Optional navigation reads through a possibly absent value without immediately throwing. Pair it with an explicit fallback when absence is an expected display state.

How it works

A selected tool may not exist before a visitor chooses one. The model declares that possibility instead of initializing an empty object that resembles a real tool. The template displays a useful prompt until the signal holds a value. Angular template optional chaining returns null for a nullish receiver, so use its documented template semantics rather than assuming every expression behaves exactly like arbitrary JavaScript.

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-null-safe-navigation',
  standalone: true,
  imports: [],
  template: `<button type="button" (click)="select()">Choose drill</button>
    <p data-result>{{ selected()?.name ?? 'Choose a tool' }}</p>`,
})
export class App {
  selected = signal<{ name: string } | null>(null);
  select(): void {
    this.selected.set({ name: 'Hand drill' });
  }
}

Expected result

Choose a tool

The first render shows the prompt and the click replaces it with Hand drill. Null-safe navigation is appropriate for an optional selection. If a required server field is missing, silently displaying a fallback may hide a data-contract error that should instead be reported.

Advertisements