I have a abc component (part of the page). It has an event mouseup.
@Component({
selector: 'abc-component'
})
@View({
<div (mousedown)="mouseDown()" (mouseup)="mouseUp()"></div>
})
export class ScheduleComponent {
mouseDown(){
//doSomthing
}
mouseUp(){}
}
But the mouseup event can only trigger when the mouse inside of the <div>
. How can I trigger the event even outside of the <div>
?
Do I have to move (mouseup)="mouseUp()"
to app.ts and then use something like @Output
or service
to let app.ts know? Is there any other way?
Thanks
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 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();
});
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With