Reputation: 181
I want to know how it's possible to get mouse coordinates X and Y using only Observables without http service using Angular 4.
Upvotes: 7
Views: 21149
Reputation: 1851
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) {
//...
}
Upvotes: 3
Reputation: 551
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.
Upvotes: 6
Reputation: 193261
Http module is not a dependency for RxJS observables, so you don't have to use it. In fact, Http module itself uses RxJS to empower Http operands with reactive capabilities.
In order to subscribe to events like mousemove
, you would simply import fromEvent
and Observable
and subscribe to its event emitter. Something like this should work:
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
Observable.fromEvent(document.body, 'mousemove').subscribe(e => {
console.log(e.pageX, e.pageY)
})
Of course, use the appropriate event source (instead of document.body
).
Upvotes: 15