path-framework-weberm16
Version:
Path Application Framework
88 lines (75 loc) • 3.24 kB
text/typescript
import {Directive, ElementRef, HostListener, Input, OnInit} from '@angular/core';
// Initially by https://github.com/cedvdb/ng2draggable
// MIT License: https://github.com/cedvdb/ng2draggable/blob/master/LICENSE
export class DraggableDirective implements OnInit{
topStart:number=0;
leftStart:number=0;
_allowDrag:boolean = true;
md:boolean;
constructor(public element: ElementRef) {}
ngOnInit(){
// draggable only for desktop version (styles for desktop are added when innerWidth>1100)
if (window.innerWidth < 1100){
this._allowDrag=false;
}
// css changes
if(this._allowDrag){
this.element.nativeElement.style.position = 'relative';
this.element.nativeElement.className += ' cursor-draggable';
}
}
set allowDrag(value:boolean){
this._allowDrag = value;
if(this._allowDrag)
this.element.nativeElement.className += ' cursor-draggable';
else
this.element.nativeElement.className = this.element.nativeElement.className
.replace(' cursor-draggable','');
}
onMouseDown(event:MouseEvent) {
let eventTargetTag:string = event.target['tagName'].toLowerCase();
if (eventTargetTag == "input" || eventTargetTag == "button" || eventTargetTag == "textarea") {
return;
}
if(event.button === 2)
return; // prevents right click drag, remove his if you don't want it
this.md = true;
this.topStart = event.clientY - this.element.nativeElement.style.top.replace('px','');
this.leftStart = event.clientX - this.element.nativeElement.style.left.replace('px','');
}
onMouseUp(event:MouseEvent) {
this.md = false;
}
onMouseMove(event:MouseEvent) {
if(this.md && this._allowDrag){
this.element.nativeElement.style.top = (event.clientY - this.topStart) + 'px';
this.element.nativeElement.style.left = (event.clientX - this.leftStart) + 'px';
}
}
onTouchStart(event:any) { // TouchEvent
this.md = true;
this.topStart = event.changedTouches[0].clientY - this.element.nativeElement.style.top.replace('px','');
this.leftStart = event.changedTouches[0].clientX - this.element.nativeElement.style.left.replace('px','');
event.stopPropagation();
}
onTouchEnd() {
this.md = false;
}
onTouchMove(event:any) { // TouchEvent
if(this.md && this._allowDrag){
this.element.nativeElement.style.top = ( event.changedTouches[0].clientY - this.topStart ) + 'px';
this.element.nativeElement.style.left = ( event.changedTouches[0].clientX - this.leftStart ) + 'px';
}
event.stopPropagation();
}
}