-
-
Save MikeRyanDev/7bc9d780aa2bb132866563346c0cc6e3 to your computer and use it in GitHub Desktop.
This file contains 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, Output, EventEmitter, ChangeDetectionStrategy, ElementRef } 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: Observable<{ x: number, y: number }>; | |
constructor(ref: ElementRef) { | |
const getMouseEventPosition = (event: MouseEvent) => ({ x: event.clientX, y: event.clientY }); | |
const mousedown$ = Observable.fromEvent(ref.nativeElement, 'mousedown').map(getMouseEventPosition); | |
const mousemove$ = Observable.fromEvent(document, 'mousemove').map(getMouseEventPosition); | |
const mouseup$ = Observable.fromEvent(document, 'mouseup'); | |
this.drag = mousedown$.switchMap(mousedown => | |
mousemove$.map(mousemove => ({ | |
x: mousemove.x - mousedown.x, | |
y: mousemove.y - mousedown.y | |
})) | |
.takeUntil(mouseup$) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment