Jeff Jeff - 6 months ago 37
Javascript Question

How to listen for click on Angular 2 element and get the event object?

I have a directive which I will apply on certain anchor elements to

preventDefault()
.

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
selector: '[myDirective]'
})
export class myDirective {

constructor(private el: ElementRef) { }

@HostListener('click') onClick(event) {
event.preventDefault() // event is undefined
}

}


What I'm trying to do is basically this in jQuery:

$('[my-directive]').click(function (e) {
e.preventDefault();
});


How can I achieve this in angular? I have Angular 4.1.

Answer Source

You need to specify the args, too:

@Directive({
  selector: '[myDirective]'
})
export class MyDirective {
  @HostListener('click', ['$event']) /* note args array */
  onClick(event) {
    console.log(event);
    event.preventDefault();
  }
}

Check out an example Plunkr: https://embed.plnkr.co/eNXEdb/ (open the console then click on "Hello Angular").