I create a custom directive for drag and drop, i don't use drag and drop from Angular material because can drag just vertical or horizontal.
The problem is for mobile touch, for touchstart and touchend the target is the same.
import { Directive, EventEmitter, HostListener, Output } from '@angular/core';
@Directive({
selector: '[appDragAndDrop]',
standalone: true,
})
export class DragAndDropDirective {
@Output() itemDrop = new EventEmitter<{ draggedIndex: number, targetIndex: number }>();
@HostListener('touchstart', ['$event'])
onTouchStart(event: TouchEvent) {
const touch = event.touches[0];
const target = touch.target as HTMLElement;
const dataIndex = target.getAttribute('data-index');
if (dataIndex) {
target.dataset['draggedIndex'] = dataIndex;
}
}
@HostListener('touchmove', ['$event'])
onTouchMove(event: TouchEvent) {
event.preventDefault();
}
@HostListener('touchend', ['$event'])
onTouchEnd(event: TouchEvent) {
const target = event.target as HTMLElement;
const targetIndex = +target.getAttribute('data-index');
const draggedIndex = +(target.dataset['draggedIndex'] || '');
if (!Number.isNaN(draggedIndex) && !Number.isNaN(targetIndex)) {
this.itemDrop.emit({ draggedIndex, targetIndex });
}
}
}
Need help, if exist another solution or show what i did wrong.
you might need to implement a way to track the movement during the drag. EG: