I have a abc component (part of the page). It has an event mouseup.
@Component({
selector: \'abc-component\'
})
@View({
Add a global event target like
<div (window:mousedown)="mouseDown()" (window:mouseup)="mouseUp()"></div>
to listen to events globally. (body
and document
work as well).
This works of course also in the components class
@HostListener('window:mouseup', ['$event'])
mouseUp(event){}
Inside the component its preferred to do as follow:
@HostListener('document:mouseup', ['$event'])
onMouseUp(event: MouseEvent) {
...
}
in this way you won't need to remove the event on ngDestroy
A bit old but this might help somebody, you can use Observable.fromEvent too:
ngOnInit() {
this.mouseUpSubscription = Observable.fromEvent(window, "mouseup")
.throttleTime(30) // throttle time in ms, optional
.subscribe(res => {
this.mouseUpHandler(res);
});
}
ngOnDestroy() {
this.mouseUpSubscription.unsubscribe();
}
A component can access events through the window
and document
objects. So you could set up an event listener in the component's constructor:
constructor() {
document.body.addEventListener("mouseup", () => {
this.mouseup();
});
}