How to get a mouse outside a component in Angular 2

I have an abc component (part of the page). He has a mouse button.

@Component({ selector: 'abc-component' }) @View({ <div (mousedown)="mouseDown()" (mouseup)="mouseUp()"></div> }) export class ScheduleComponent { mouseDown(){ //doSomthing } mouseUp(){} } 

But the mouseup event can only be fired when the mouse is inside the <div> . How can I trigger an event even outside of the <div> ?

Do I need to move (mouseup)="mouseUp()" in app.ts and then use something like @Output or service to tell app.ts ? Is there another way?

thanks

+5
source share
3 answers

Add a global goal, e.g.

 <div (window:mousedown)="mouseDown()" (window:mouseup)="mouseUp()"></div> 

to listen to events around the world. ( body and document ).

This, of course, also works in the component class.

 @HostListener('window:mouseup', ['$event']) mouseUp(event){} 
+8
source

A component can access events through window and document objects. Thus, you can configure the event listener in the component constructor:

 constructor() { document.body.addEventListener("mouseup", () => { this.mouseup(); }); } 
+1
source

Inside the component, it is preferable to do the following:

 @HostListener('document:mouseup', ['$event']) onMouseUp(event: MouseEvent) { ... } 

this way you will not need to delete the event on ngDestroy

+1
source

Source: https://habr.com/ru/post/1242649/


All Articles