Gregg Pollack Gregg Pollack - 1 year ago 180
Javascript Question

angular 2 event binding - Do I need $event?

I've noticed that with Angular 2, unlike the documentation, when I do event binding I don't have to pass $event to access event data from a component method. So the following code works fine:

In the template:

<h2 (mouseover)="getCoord()" >Random Words</h2>

In the component:

getCoord() {
console.log(event.clientX + ", " + event.clientY);

This works perfectly, without the need to pass the $event object through to the method.

Is this okay? Is this now the preferred method, but the documentation doesn't show it? Seems fine to me.

Answer Source

I'd consider this a bug in Angular and wouldn't build on it to keep working.

There is for example the @HostListener() decorator that has an explicit args parameter where you define if $event or $ or some other event property should be passed.

There is some optimization going on for communication between WebWorker and UI thread where only the part of the event is serialized and passed between these threads that is defined in the args. I assume something similar is happening with the kind of event binding you use in your question.