bhylu.com

Advertisements

Angular Events and $event

An event binding connects a DOM event to a component operation. $event is the actual event object; narrow its target before reading element-specific properties.

How it works

The desk filter accepts text from a labeled input. The handler verifies that the target is an HTMLInputElement before reading value, then writes a trimmed signal. That keeps DOM assumptions in one place instead of scattering casts through the template. Event handlers should make state changes understandable and avoid unrelated side effects on every keystroke.

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-events',
  standalone: true,
  imports: [],
  template: `<label>Tool filter<input (input)="filter($event)" /></label>
    <p data-result>{{ query() || 'All tools' }}</p>`,
})
export class App {
  query = signal('');
  filter(event: Event): void {
    const target = event.target;
    if (target instanceof HTMLInputElement) this.query.set(target.value.trim());
  }
}

Expected result

All tools

Typing clamp updates the paragraph to clamp. The handler models the browser event rather than assuming every target has a value property. For an emitted component event, $event may be a domain value instead of a DOM Event; the child’s output type defines that contract.

Advertisements