Differentiate The Click And Drag Event In Material Drag And Drop With Position

The problem with the dragging of the element is that whenever we drag the element then it also triggers the click events. In this article, we use the material drag and drop for creating the draggable element with the cdkDrag. 

Let’s start:

Step 1: Import the DragDropModule into the app.module.ts

import {DragDropModule} from '@angular/cdk/drag-drop';

Step 2: Add the cdkDragStarted and cdkDragEnded in the app.component.ts

<div class="drag-box" cdkDragLockAxis="x" cdkDrag (click)="handleClick($event)" (cdkDragStarted)="handleDragStart($event)" (cdkDragEnded)="handleDragEnd($event)">
  Drag me or click me!
</div>

Step 3: Add the method to the app. component.html

import { CdkDragEnd, CdkDragStart } from '@angular/cdk/drag-drop';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  title = 'MatDragAndDrop';

  dragging: any;
  
  constructor() {
  }

  public handleClick(event: MouseEvent): void {
    if (this.dragging) {
      this.dragging = false;
      return
    }
    alert('clicked');
  }

  public handleDragStart(event: CdkDragStart): void {
    this.dragging = true;
  }

  handleDragEnd(event: CdkDragEnd): void {
    alert('Distance: X = ' + event.distance.x + ' Y = ' + event.distance.y + '\n' + 'Position: X = ' + event.dropPoint.x + ' Y = ' + event.dropPoint.y);
  }
}

Step 4: Add the style.

.drag-box {
    width: 150px;
    height: 150px;
    border: solid 1px #ccc;
    color: rgba(0, 0, 0, 0.87);
    cursor: move;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    background: #fff;
    border-radius: 4px;
    margin-top: 16rem;
    position: relative;
    z-index: 1;
    transition: box-shadow 200ms cubic-bezier(0, 0, 0.2, 1);
    box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2),
                0 2px 2px 0 rgba(0, 0, 0, 0.14),
                0 1px 5px 0 rgba(0, 0, 0, 0.12);
  }
  
  .drag-box:active {
    box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
                0 8px 10px 1px rgba(0, 0, 0, 0.14),
                0 3px 14px 2px rgba(0, 0, 0, 0.12);
  }

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories