angularangular-cdkangular-cdk-drag-drop

The position of source element rectangle position is confusion in angular cdkDragStarted


I am locating the offset position of mouse point when drag a div, suppose to be mouse.x-div.x is all I need, but the div.x is a large negative number(-15984). I am wondering why, and how to resolve the issue.

HTML:

@for (comp of components; track comp) {
<div #componentContainer class="component-container" (cdkDragStarted)="beforeDrag($event)" cdkDrag cdkDropList [cdkDropListConnectedTo]="container">
  <div class="component-wapper">
    <div class="component-name"> {{comp.name}}</div>
    <img class="component-avatar" src="{{comp.src}}" />
  </div>
</div>
}

Typescript:

var rect = e.source.element.nativeElement.getBoundingClientRect();
console.log(rect.x)

Solution

  • You have to access the previousElementSibling instead of the actual element, since this is the drag element in the container.

    beforeDrag(e: any) {
        const mouseX = e.event.x;
        const rect =
          e.source?.element?.nativeElement?.previousElementSibling?.getBoundingClientRect();
        console.log('needed value', mouseX - rect.x);
    }
    

    Stackblitz Demo