bhylu.com

Advertisements

Angular Effects

An effect coordinates reactive state with a non-reactive API. Use it for deliberate side effects, and register cleanup when an old run or a destroyed owner must release a resource.

How it works

The example synchronizes a tool count with the document title. The view still reads the count directly; the effect is not used to maintain a duplicate total signal. Capturing the previous title and restoring it during cleanup makes ownership visible. Effects run in an Angular injection context, and their scheduling differs from an ordinary synchronous function call.

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 { effect, inject, signal } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'bh-effects',
  standalone: true,
  imports: [],
  template: `<button type="button" (click)="count.set(2)">Update count</button>
    <p data-result>{{ count() }} {{ count() === 1 ? 'tool' : 'tools' }}</p>`,
})
export class App {
  count = signal(1);
  private doc = inject(DOCUMENT);
  constructor() {
    effect((onCleanup) => {
      const before = this.doc.title;
      this.doc.title = 'Tools ' + this.count();
      onCleanup(() => {
        this.doc.title = before;
      });
    });
  }
}

Expected result

1 tool

After the click, the screen says 2 tools and the document title becomes Tools 2. The review waits for the reactive update before asserting the external title. Accessing browser APIs must also be considered separately when rendering on the server.

Advertisements