Search code examples
javascriptcssangularangular-cdk

Angular CDK drag and drop - is it possible to create circular boundary?


Is it possible to restrict an Angular Drag and Drop element to a circular boundary?

Looking at the documentation below

Restricting movement within an element

If you want to stop the user from being able to drag a cdkDrag element outside of another element, you can pass a CSS selector to the cdkDragBoundary attribute. The attribute works by accepting a selector and looking up the DOM until it finds an element that matches it. If a match is found, it'll be used as the boundary outside of which the element can't be dragged. cdkDragBoundary can also be used when cdkDrag is placed inside a cdkDropList.

I tried changing the css (see stackblitz) to be circular but my understanding from the result is this only changes the appearance and not the boundary of the DOM element.

With everything in the DOM essentially being a rectangle does this mean circular or very close to a circle restriction is not possible?

https://stackblitz.com/edit/angular-gughvc


Solution

  • As far as I can tell, there's no direct way to do what you want.

    However, you could probably monitor the drag, do a "hit test" for your circular boundary, and stop the drag yourself when the boundary is exceeded.

    I did a quick-and-dirty test at https://stackblitz.com/edit/angular-ut9fgz

    This stops the drag at the mid-point of the circle, but:

    • It doesn't just prohibit going past the boundary, it cancels the drag.

    • Having a callback for every drag event (essentially every pixel traversed) can be expensive - your "hit test" better be very efficient.

    So, this shows the general concept, but there's still a lot left to be worked out.

    Besides the official documentation, the following pages might be helpful:

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

    Cancel drag on key press Angular cdk Drag and Drop