I am trying to implement a draggable functionality with HammerJs and Angular but my element does not move. The mouse points are printed out but the element does not move.
@Component({
selector: 'app-example',
styles: ['.demo-one {width:200px;height:200px;background-color: slateblue;color: #fff;}',
'.demo-one:hover {cursor:pointer}'],
template: `<div class="demo-one" [style.marginleft.px]="x" [style.margintop.px]="y"
(panstart)="onPanStart($event)" (panmove)="onPan($event)">
<div class="label">{{title}}</div>
<div class="location">({{x}}, {{y}})</div>
</div>`
})
export class ExampleComponent implements OnInit {
x = 0;
y = 0;
title = 'Drag Me!';
startX = 0;
startY = 0;
constructor() { }
ngOnInit() {
}
onPanStart(event: any): void {
this.startX = this.x;
this.startY = this.y;
}
onPan(event: any): void {
event.preventDefault();
this.x = this.startX + event.deltaX;
this.y = this.startY + event.deltaY;
}
}
I think you should use position: absolute
for the draggable element and set its left
and top
instead of marginleft
and margintop
when dragging it. By doing that, the element will be moved more freely.
Check the following:
styles: ['.demo-one {position: absolute; width:200px;height:200px;background-color: slateblue;color: #fff;}','.demo-one:hover {cursor:pointer}']
template: `<div class="demo-one" [style.left]="x" [style.top]="y (panstart)="onPanStart($event)" (panmove)="onPan($event)">