8

With the new drag and drop feature of the @angular/cdk (I'm currently using version 7.0.0-beta.2), is it possible to cancel a drag-action?

I did not find a matching function on 'CdkDrag' which could do the trick.

Edit from 2019-01-10

Thanks for the responses so far. I guess I wasn't clear enough, though: I'm looking for a way to cancel a drag-action which is already in progress. I. e. while dragging an item, I want to have the possibility to make that item return to the container where it comes from (e. g. by pressing the Escape key).

Any ideas?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

4 Answers4

6

it's not possible with anguar 7.0.0, you have to update to angular 7.1.0, then you have:

[cdkDragDisabled]="condition"

which works perfect!

cucuru
  • 3,456
  • 8
  • 40
  • 74
  • Can I show moving the same card as it through CSS. As in the image (link) it is showing moving text data not the whole card (with CSS styles) https://medium.com/@er.markar/can-i-show-moving-the-same-card-as-it-through-css-9edda248094 – Sunil Garg Aug 14 '19 at 06:11
2

If you want to disable dragging for a particular drag item, you can do so by setting the cdkDragDisabled input on a cdkDrag item.

<div cdkDropList class="list" (cdkDropListDropped)="drop($event)">
<div *ngFor="let item of dragedItems" cdkDrag 
[cdkDragDisabled]="item.disabled"> {{item.value}} </div>
</div>
Mohd. Shariq
  • 214
  • 3
  • 14
2

A reset function has recently been added to CdkDrag.

As example, if you have the following draggable div:

<div cdkDrag (cdkDragEnded)="onDragEnded($event)"></div>

You can restore it to its original position like this:

onDragEnded(event: CdkDragEnd): void {
    if (condition) {
        event.source._dragRef.reset();
    }
}

https://github.com/angular/components/issues/13661

AleRubis
  • 284
  • 4
  • 10
0

I was looking for that feature for ages. Turns out, it is simple enough:

private _canceledByEsc = false;

@HostListener('window:keyup', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
    if (event.key === 'Escape') {
        this._canceledByEsc = true;
        document.dispatchEvent(new Event('mouseup'));
    }
}

handleDrop() {
    if (!this._canceledByEsc) {
        // probably just return and don't do any array manipulations
    }
}

(seen on Cancel drag on key press Angular cdk Drag and Drop)