liveBook · Manning

Host listener

As explained in Pro Angular 16

@HostListener is an Angular decorator that binds a directive or component method to an event on its host element.

@HostListener is an Angular decorator that connects a directive or component method to an event on its host element. Angular creates the listener, so the directive can respond without directly calling addEventListener or accessing ElementRef. section 14.5

Use a host listener when a directive needs to react to activity on its host element:

  • Name the event in the decorator's first argument, such as @HostListener("input"). section 14.6
  • Pass event-derived values through a second argument array, such as ["$event.target.value"]. section 14.6
  • Update directive state and emit an output when the handler runs. section 14.6

Forwarding an input value

A directive can combine a host binding, host listener, and output to create a simple two-way model binding: @HostListener("input", ["$event.target.value"]) updateValue(newValue: string) { this.fieldValue = newValue; this.update.emit(newValue); } The input event supplies the host element's current value to updateValue. The method updates the value binding and emits paModelChange, allowing [(paModel)]="newProduct.name" in the template. section 14.6

How Pro Angular 16 covers it

How deep it goes
Explains decorator arguments and event-value extraction, while deferring listener internals to Angular's browser or alternate-environment implementation.
Examples
Uses click handling on table rows and input handling for a custom two-way model directive.
What it assumes
Assumes familiarity with Angular directives, decorators, input and output properties, and template bindings.
What you can do after
Build it from scratch by declaring a host event, extracting event values, updating state, and emitting an output.
How it connects
Ties host listeners to host binding, event binding, directives, input properties, output properties, and EventEmitter.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.