2

Hey I'm using Angular material Drag and drop. Everything is working fine but after each drag it triggers the click event and it's really annoying. How can I stop this?

<div
  cdkDrag
  [cdkDragDisabled]="shiftWorker.locked"
  (cdkDragEnded)="onDragEnded(job, shiftWorker, $event)"
  (cdkDragStarted)="onDragStart($event)"
  [cdkDragData]="job"
  *ngIf="job.timelineInfo.isInDayShift === firstHalfDay"
  (click)="openWorkDetails(job.id)"
></div>
Manoj
  • 2,000
  • 2
  • 16
  • 21
eixcs
  • 1,957
  • 4
  • 15
  • 37
  • In the body of `onDragEnded` add `$event.preventDefault();`. Does that fix the issue? (*this assumes that `$event` is also the name of the 3rd parameter in that method*) – Igor Jun 12 '19 at 10:43
  • @Igor Tried that. When using this, the dragEnd functionality doesn't work, but the click event still happens :/ – eixcs Jun 12 '19 at 10:45
  • Have you tried $event.stopPropagation() ? – Tim Jun 12 '19 at 10:53
  • @Tim doesn't change anything sadly – eixcs Jun 12 '19 at 10:56

2 Answers2

6

You can use a boolean to keep a track of this situation:

 var dragging = false;
 (cdkDragStarted): function(event, ui) {
    dragging = true;
    ...your code
 }

(click): function(event) {
    if (!dragging) {
        ...your code
    }
    else {
        dragging = false;
    }
});
Priyesh Diukar
  • 2,032
  • 1
  • 15
  • 19
5

Turning off pointer events for the element while it's being dragged prevents a click event afterwards:

template:

<div cdkDrag #draggable="cdkDrag" 
     [class.pointer-events-none]="draggable._dragRef.isDragging()" ...

styles.scss:

.pointer-events-none {
  pointer-events: none;
}
Martin Cremer
  • 5,191
  • 2
  • 32
  • 38