@HostListener
is a decorator for the callback/event handler method, so remove the ;
at the end of this line:
@HostListener('click', ['$event.target']);
Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick()
method on the same line for clarity:
import {Component, HostListener, Directive} from 'angular2/core';
@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: 'my-app',
template: `<button counting>Increment</button>`,
directives: [CountClicks]
})
export class AppComponent {
constructor() { console.clear(); }
}
Host binding can also be used to listen to global events:
To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }