Created
April 14, 2017 20:27
-
-
Save amcdnl/58ffee44190db7ea101cc1cf869fb3d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, Input, Output, EventEmitter, ChangeDetectionStrategy, HostListener } from '@angular/core'; | |
import { Observable } from 'rxjs/Observable'; | |
import { Subscription } from 'rxjs/Subscription'; | |
import 'rxjs/add/operator/takeUntil'; | |
@Directive({ | |
selector: '[draggable]', | |
changeDetection: ChangeDetectionStrategy.OnPush | |
}) | |
export class DraggableDirective { | |
@Output() drag = new EventEmitter(); | |
private mouseup$: Subscription; | |
private mousemove$: Subscription; | |
@HostListener('mousedown', ['$event']) | |
onMouseDown(event: MouseEvent): void { | |
const mouseDownPos = { x: event.clientX, y: event.clientY }; | |
const mouseup = Observable.fromEvent(document, 'mouseup'); | |
mouseup.subscribe((ev: MouseEvent) => this.onMouseup(ev)); | |
this.mousemove$ = Observable | |
.fromEvent(document, 'mousemove') | |
.takeUntil(mouseup) | |
.subscribe((ev: MouseEvent) => this.onMouseMove(ev, mouseDownPos)); | |
} | |
onMouseMove(event: MouseEvent, mouseDownPos: { x: number, y: number }): void { | |
const x = event.clientX - mouseDownPos.x; | |
const y = event.clientY - mouseDownPos.y; | |
this.drag.emit({ x, y }); | |
} | |
onMouseup(ev): void { | |
this.mouseup$.unsubscribe(); | |
this.mousemove$.unsubscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment