Skip to content

Instantly share code, notes, and snippets.

@MikeRyanDev
Forked from amcdnl/draggable.ts
Last active May 5, 2017 02:47
Show Gist options
  • Save MikeRyanDev/7bc9d780aa2bb132866563346c0cc6e3 to your computer and use it in GitHub Desktop.
Save MikeRyanDev/7bc9d780aa2bb132866563346c0cc6e3 to your computer and use it in GitHub Desktop.
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