Search code examples
angularangular-materialangular-cdk

Differentiate cdkDrag and click in angular


I have a draggable element for which I have used cdkDrag and it is working fine for me. Now, I need to toggle a flag on click of the element. But when I drag the element and on drop the click event triggers. Can you please suggest how to work with cdkDrag and click together. Sharing the code snippet for the same.

        <div class="draggable-content" cdkDragBoundary=".drop-area" cdkDrag>
          <div class="min-workspace-view" *ngIf="showMinWorkspace === true">
            <mat-icon svgIcon="workspace" class="workspace-icon"
              (click)="$event.stopPropagation(); showMinWorkspace = !showMinWorkspace">
            </mat-icon>
          </div>
        </div>

The expectation is: when the element dragged then click should not trigger. when the element is just clicked then drag event should not trigger.


Solution

  • I got a solution to this.

    You need a boolean property. Let's call it dragging.

    On your cdkDrag element, add a cdkDragStarted callback, which sets this property to true. Then in your click callback, if that this.dragging is true, then set it to false and return. Hey Presto!

    working stackblitz here https://stackblitz.com/edit/angular-drag-drop-and-clickable-element