Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing placeholder for drop area when cursor not in drop zone in material cdk drag & drop

When drag item moves over the drop area, the area is highlighted and created a placeholder for the same. But if the mouse point is moving away the drop area and release the drop the item. It still drop into the drop zone.

Drag Drop Issue Demo

Expected behavior:

Once the mouse pointer is move away from the drop zone and the user release the mouse or cancel the drag. It should go back to the drag start list.

stackblitz

like image 798
tabinda Avatar asked Oct 28 '25 18:10

tabinda


1 Answers

Basically, you want to check, when the item was dropped, whether it was allowed container or not.

We can use CdkDrag's cdkDragDropped event. cdkDragDropped emits the object which has a type of interface CdkDragDrop. CdkDragDrop has a property called isPointerOverContainer: boolean, which returns whether the user's pointer was over the container when the item was dropped.

I have created a sample code on stackblitz.

Basically, what I did was:

  1. Listened to cdkDragDropped event of cdkDrag element : <div class="example-box" *ngFor="let item of todo" cdkDrag (cdkDragDropped)="dragDropped($event)">{{item}}</div>
  2. In dragDropped function, I stored the flag: dragDropped(event: CdkDragDrop<string[]>) { this.isPointerOverContainer = event.isPointerOverContainer; }
  3. In drop function, I checked the same flag : if (this.isPointerOverContainer) {...} else { //dropped outside }

Currently, the item will get back to its original position if dropped outside. But, the animation is not handled, you can explore that part.

like image 93
shhdharmen Avatar answered Oct 30 '25 09:10

shhdharmen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!