I want to know how it's possible to get mouse coordinates X and Y using only Observables without http service using Angular 4.
I want to know how it's possible to get mouse coordinates X and Y using only Observables without http service using Angular 4.
This question is pretty old but seems to draw some attention by using google. The answer above is totally correct and i just want to give a brief hint for people looking for a Angular 9 solution (and maybe below).
Using Angular Directives alongside with the decorator @HostListener we can add DOM event listeners as follows:
Inside your Angular Directive class:
@Directive({
selector: '[appMousePosition]'
})
export class MosuePositionDirective {
...
@HostListener('mousemove', ['$event']) onMouseMove(event) {
console.log(event.clientX, event.clientY);
}
}
Inside your HTML source:
<div appMousePosition ...> </div>
If the client's mouse is moving inside the visible <div> element the Event will fire.
See Angular's documentation about @HostListeners 1 and Angular's Directives 2 for further details.
If you want to track the mouse coordinates only on a certain element, you can also use mousemove like an Output directly on an html element.
Template:
<div (mousemove)="mouseMoved($event)"></div>
Typescript:
mouseMoved(event: MouseEvent) {
//...
}