2

I'm trying to get the x and y position of a box based on the position inside the container. Here's an example from https://material.angular.io.

I currently have this small demo to check the output of the cdkDragMoved event.

<div class="something">
  <div class="example-box" cdkDrag cdkDragBoundary=".something" (cdkDragMoved)="test($event)" (cdkDragEnded)="test($event)" (cdkDragReleased)="test($event)">
    Drag me around
  </div>
</div>
export class CdkDragDropOverviewExample {
  test(e) {
    console.log(e)
  }
}

The desired output I would like is the position relative to the parent in either pixels or percentages.

servinlp
  • 715
  • 1
  • 8
  • 17

1 Answers1

2

There might be more elegant ways, but here's how I did it.

  1. Using @ViewChild, get an ElementRef for the parent element and also the item being dragged. From that, we can access the nativeElement to get a reference to the DOM elements
  2. Figure out the top-left corner of the item being dragged by subtracting the top corner of the item being dragged (which can be found by calling getBoundingClientRect() on the element) from the pointer position (from the onDragMoved event)
  3. Figure out the top-left corner of the parent element too using the same technique
  4. Using the two values above, you can infer what the position of the dragged element is relative to the parent element in pixels, by taking pointer position - distance from corner of dragged element - position of the parent element relative to the page

Here is an example in StackBlitz.

Matt Wilson
  • 8,159
  • 8
  • 33
  • 55
  • It's works fine for one single draggable element inside boundary. But how to achieve same result with multiple draggable items. In my project having multiple draggable elements(different cases) inside boundary. Please let me know how to achieve it. – sankar muniyappa Dec 05 '22 at 16:25