@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
