Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mouseup outside of the component in Angular 2

Tags:

angular

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

like image 630
Hongbo Miao Avatar asked Feb 09 '16 20:02

Hongbo Miao


4 Answers

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){}
like image 66
Günter Zöchbauer Avatar answered Oct 13 '22 22:10

Günter Zöchbauer


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

like image 25
Sabri Aziri Avatar answered Oct 13 '22 22:10

Sabri Aziri


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(); 
  });
}
like image 2
MatthewScarpino Avatar answered Oct 13 '22 22:10

MatthewScarpino


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();
}
like image 2
remborg Avatar answered Oct 13 '22 21:10

remborg