I´m working in a application implementing the new drag and drop from angular material CDK and i´m trying to cancel the drag event of the element pressing Esc
, i
Here's a version using rxjs. It requires a reference to CdkDrag
as ViewChild. Unfortunately, because there is no public method to stop dragging on the DragRef
you have to use dispatchEvent
as the only way to end the dragging process.
There are two parts in the example below. What's happening is that the ended event can only be listened to after a start, and that instance of listening can be stopped by a subject triggered by pressing escape.
CdkDrag
directive.takeUntil
operator, and reset()
will be called on the directive to reset the position and dispatchEvent()
will be used to stop the drag process.onDragEnded()
method is called from the OP.take(1)
.private dragCancelRequest = new Subject();
ngAfterViewInit() {
this.drag.started.pipe(
switchMap(({ source }) => source.ended.pipe(
takeUntil(this.dragCancelRequest.pipe(tap(() => {
source.reset();
document.dispatchEvent(new Event('mouseup'));
})))
)),
tap(x => this.onDragEnded(x))
).subscribe();
}
@HostListener('window:keyup', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Escape') {
this.dragCancelRequest.next();
}
}