Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass mouseevent to component onclick

I'm trying to capture mouse coordinates in a Angular component.

Here is the html in question:

<div id="container" class="fullSize" style="height:100%;" (click)="onClick(ev)"></div>

Here is the component function in the corresponding typescript file:

onClick( ev : MouseEvent ) {
  console.log("x:" + ev.clientX);
}

And the error in the console:

Cannot read property 'clientX' of undefined'

What would be the correct way of passing that MouseEvent to my component function?

like image 654
Clinton J Avatar asked Mar 08 '23 00:03

Clinton J


2 Answers

You should use $event to pass MouseEvent object to your click handler.

So simply write:

(click)="onClick($event)"

See also

  • https://angular.io/guide/template-syntax#event-and-event-handling-statements
like image 116
yurzui Avatar answered Mar 20 '23 19:03

yurzui


Current best practice:

<div id="container" class="fullSize" style="height:100%;" (click)=onClick($event.clientX)"></div>
onClick(myClientX: number) { 
  console.log("x: " + myClientX);
}

Per current guideline found here: Passing $event is a dubious practice

like image 44
Reid Avatar answered Mar 20 '23 19:03

Reid