Help Angular by taking a 1 minute survey!Go to surveyHome

HostListener

Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.

OptionDescription
eventName

The CSS event to listen for.

args

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

Options

The CSS event to listen for.

eventName: string
      
      eventName: string
    

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

args: string[]
      
      args: string[]
    

Usage notes

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 {}
      
      
  1. @Directive({selector: 'button[counting]'})
  2. class CountClicks {
  3. numberOfClicks = 0;
  4.  
  5. @HostListener('click', ['$event.target'])
  6. onClick(btn) {
  7. console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
  8. }
  9. }
  10.  
  11. @Component({
  12. selector: 'app',
  13. template: '<button counting>Increment</button>',
  14. })
  15. class App {}