Angular Material CDK Drag and Drop Snap To Grid Internal Element cdkDragConstrainPosition @Input for element inside the Drag and Drop element position

Viewed 705

When using Drag and Drop via Angular Material CDK, it allows you to "snap to grid" via [cdkDragConstrainPosition]="computedDragRenderPos"

Example:

<div cdkDrag [cdkDragConstrainPosition]="computeDragRenderPos">
  ...
</div>
export class MyDraggableComponent {

  constructor() {}

  computeDragRenderPos(pos, dragRef) {
    return {x: Math.floor(pos.x / 30) * 30, y: pos.y}; // will render the element every 30 pixels horizontally
  }
}

However, that passes in pos which is the mouse pos. I understand you can pass dragRef and get the element's getBoundingClientRect to get the x but as soon as you pass that into the cdkDragConstrainPosition position and change the position of the element it no longer works.

How do you move an internal element every 30px.... and not the position of the start of the element?

1 Answers

i have close issue

dragRef it is a ref to dragable element if you want snap to some grid you need to calculate position depend on other element

@ViewChild("someElement") someElement;

computeDragRenderPos(pos, dragRef) {
    return {
       x: this.someElement.nativeElement.getBoundingClientRect().x,
       y: this.someElement.nativeElement.getBoundingClientRect().y };
  }

you need to include some cursor logic here to keep it work

in my case it is also lost scope of the component class for some reason (not sure it was personal problem or global) i solve it with bind(this) before pass function to cdkDragConstrainPosition

Related