Jeff Jeff - 1 year ago 81
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


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

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) {

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

Answer Source

You need to specify the args, too:

  selector: '[myDirective]'
export class MyDirective {
  @HostListener('click', ['$event']) /* note args array */
  onClick(event) {

Check out an example Plunkr: (open the console then click on "Hello Angular").

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download