Search code examples
angulardrag-and-dropangular-materialangular-cdk

Get drop position of item in cdkDropList


I'm trying to get (or calculate) the x/y coordinates of a dropped item in an angular-material cdkDropList. I've studied the documentation https://material.angular.io/cdk/drag-drop/api#CdkDragDrop and found there should be a property called "distance" in the CdkDragDrop interface but I can't find it in the console log of the event:

drop(event: CdkDragDrop<string[]>) {
    console.log(event);
}

I've only found container, currentIndex, item, previousContainer, previousIndex. By the way: I'm new to angular and this and the documentation confuses me :(

thx and greetings


Solution

  • Ok, forget it... the property distance was introduced in version 8.0.1 and I'm on 7.1.0...

    Update

    To get the position in this version you can use the cdkDragMoved event like shown here:

    https://grokonez.com/frontend/angular/angular-7/angular-7-drag-and-drop-example-angular-material-cdk

    html Part:

    <div cdkDrag class="drag-box"
      (cdkDragStarted)="dragStarted($event)"
      (cdkDragEnded)="dragEnded($event)"
      (cdkDragMoved)="dragMoved($event)"
    >
      drag me
    </div>
    <p>{{state}} {{position}}</p>
    

    and in TypeScript:

    import { CdkDragEnd, CdkDragStart, CdkDragMove } from '@angular/cdk/drag-drop';
    ...
    export class DragComponent implements OnInit {
      state = '';
      position = '';
      ...
    
      dragStarted(event: CdkDragStart) {
        this.state = 'dragStarted';
      }
    
      dragEnded(event: CdkDragEnd) {
        this.state = 'dragEnded';
      }
    
      dragMoved(event: CdkDragMove) {
        this.position = `> Position X: ${event.pointerPosition.x} - Y: ${event.pointerPosition.y}`;
      }
    }