Cancel drag on key press Angular cdk Drag and Drop

后端 未结 5 481
醉话见心
醉话见心 2021-01-11 23:16

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

5条回答
  •  情深已故
    2021-01-11 23:30

    I also faced this problem for a long time. Finally I could fix it by dispatching a mouseup event that will act as the user releasing the mouse.

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

    This is an extremely hacky solution and comes with it's down sides. In fact, you are not cancelling the drag but instead dropping. Meaning that if you are hovering a cdkDropList or one is active it will trigger the cdkDropListDropped emmiter for that list. Something you can easily workaround by adding a flag.

    private _canceledByEsq = false;
    
    @HostListener('window:keyup', ['$event'])
    handleKeyboardEvent(event: KeyboardEvent) {
        if (event.key === 'Escape') {
            this._canceledByEsq = true;
            document.dispatchEvent(new Event('mouseup'));
        }
    }
    
    handleDrop() {
        if (!this._canceledByEsq) {
            // Do my data manipulations
        }
    }
    

    Hope this helps you... :)

提交回复
热议问题