@HostListener

This is the documentation for Angular 6.
You can switch to the latest version Angular 7.

Binds a CSS event to a host listener and supplies configuration metadata. Angular invokes the supplied handler method when the host element emits the specified event, and updates the bound element with the result.

If the handler method returns false, applies preventDefault on the bound element.

Example

The following example declares a directive that attaches a click listener to a button and counts clicks.

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;

  @HostListener('click', ['$event.target'])
  onClick(btn) {
    console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
 }
}

@Component({
  selector: 'app',
  template: '<button counting>Increment</button>',
})
class App {}
Tutorials

Options

@HostListener(eventName: string, args: string[])

eventName#

The JavaScript event to listen for.

eventName: string

args#

A set of arguments to pass to the handler method when the event occurs.

args: string[]