Home > database >  Angular Material Drag and Drop cdkDragConstrainPosition not scoped to component
Angular Material Drag and Drop cdkDragConstrainPosition not scoped to component

Time:06-14

I am using CDK drag and drop in my project. Inside the method: cdkDragConstrainPosition I am computing a 'snap' to columns in my component. When this method is called, I can't access any of my component level variables. They are all undefined. When I do console.log(this) it outputs DragRef so the scope set to the component. How can I access my component level variables inside this function?

<div cdkDrag cdkDragBoundary=".drag-boundary" [cdkDragData]="{'colwidth': colWidth}" [cdkDragConstrainPosition]="computeDragRenderPos" [style.width.px]="colWidth" style="position: absolute; transform: translate3d(80px, 177px, 0px); background-color: beige; top: 0; left: 0; height: 42px; overflow: hidden">
    <div>Chris's awesome presentation. Doing fun stuff with science</div>
  </div>

Relevant Component code:

computeDragRenderPos(pos, dragRef, clientRect) {
    console.log(this);
    console.log(this.myComponentVariable); //this is undefined

}

CodePudding user response:

This is because cdkDragConstrainPosition accepts function as a parameter and not a value. So the function is called in the scope of directive that uses it as an input, hence this is not your component. You can define your function using arrow function to preserve the scope. Try something like this (from the top of my head):

computeDragRenderPos = (userPointerPosition: Point, dragRef: DragRef,
  dimensions: ClientRect): Point => {
      //console.log(this.myComponentVariable);
}
  • Related