How to get mouseup outside of the component in Angular 2

后端 未结 4 1886
一生所求
一生所求 2021-01-12 01:03

I have a abc component (part of the page). It has an event mouseup.

@Component({
    selector: \'abc-component\'
})
@View({
    
相关标签:
4条回答
  • 2021-01-12 01:15

    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){}
    
    0 讨论(0)
  • 2021-01-12 01:21

    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

    0 讨论(0)
  • 2021-01-12 01:24

    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();
    }
    
    0 讨论(0)
  • 2021-01-12 01:27

    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(); 
      });
    }
    
    0 讨论(0)
提交回复
热议问题