Check out my code on Plunker for drag and drop functionality in drag.ts: http://plnkr.co/edit/PITLKzBB6YXobR1gubOw?p=preview. Please note that it only works in a separate window preview.
import {Component, OnInit, ElementRef, Renderer} from '@angular/core'
@Component({
selector: 'my-drag',
template: `
<div class="drag"
draggable="true"
(dragstart)="onDragStart($event)"
(dragend)="onDragEnd($event)"
(drag)="onDrag($event)">
drag
</div>
`,
styles: ['.drag {width: 50px; height: 50px; border: 1px solid black; background-color: red;}']
})
export class DragComponent implements OnInit {
private dx: number = 0;
private dy: number = 0;
constructor(private el: ElementRef, private renderer: Renderer) { }
ngOnInit() {
this.renderer.setElementStyle(this.el.nativeElement, 'position', 'absolute');
}
onDragStart(event: MouseEvent) {
this.dx = event.x - this.el.nativeElement.offsetLeft;
this.dy = event.y - this.el.nativeElement.offsetTop;
}
onDrag(event: MouseEvent) {
this.move(event.x, event.y);
this.renderer.setElementAttribute(this.el.nativeElement, 'draggable', 'false');
}
onDragEnd(event: MouseEvent) {
this.dx = 0;
this.dy = 0;
}
move(x: number, y: number) {
if (!x || !y) return;
this.renderer.setElementStyle(this.el.nativeElement, 'top', (y - this.dy) + 'px');
this.renderer.setElementStyle(this.el.nativeElement, 'left', (x - this.dx) + 'px');
}
}
There are a couple of issues with the implementation:
- Duplicated div appears when dragged - how can this be fixed?
- Cursor changes during drag - how do I set it back to default?
Thank you for your help!