Skip to content

Commit 68a5f35

Browse files
crisbetommalerba
authored andcommitted
fix(drag-drop): error on touch end (#14392)
Fixes an error being thrown by `CdkDrag` when the `touchend` event fires. Fixes #14390. Marking as P2 since this will throw consistently on touch devices.
1 parent d69d5fb commit 68a5f35

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/cdk/drag-drop/drag.spec.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1782,6 +1782,30 @@ describe('CdkDrag', () => {
17821782
.toEqual(['Zero', 'One', 'Two', 'Three']);
17831783
}));
17841784

1785+
it('should not throw if the `touches` array is empty', fakeAsync(() => {
1786+
const fixture = createComponent(DraggableInDropZone);
1787+
fixture.detectChanges();
1788+
const item = fixture.componentInstance.dragItems.toArray()[1].element.nativeElement;
1789+
1790+
dispatchTouchEvent(item, 'touchstart');
1791+
fixture.detectChanges();
1792+
1793+
dispatchTouchEvent(document, 'touchmove');
1794+
fixture.detectChanges();
1795+
1796+
dispatchTouchEvent(document, 'touchmove', 50, 50);
1797+
fixture.detectChanges();
1798+
1799+
expect(() => {
1800+
const endEvent = createTouchEvent('touchend', 50, 50);
1801+
Object.defineProperty(endEvent, 'touches', {get: () => []});
1802+
1803+
dispatchEvent(document, endEvent);
1804+
fixture.detectChanges();
1805+
}).not.toThrow();
1806+
1807+
}));
1808+
17851809
});
17861810

17871811
describe('in a connected drop container', () => {

src/cdk/drag-drop/drag.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -747,7 +747,8 @@ export class CdkDrag<T = any> implements AfterViewInit, OnDestroy {
747747

748748
/** Determines the point of the page that was touched by the user. */
749749
private _getPointerPositionOnPage(event: MouseEvent | TouchEvent): Point {
750-
const point = this._isTouchEvent(event) ? event.touches[0] : event;
750+
// `touches` will be empty for start/end events so we have to fall back to `changedTouches`.
751+
const point = this._isTouchEvent(event) ? (event.touches[0] || event.changedTouches[0]) : event;
751752

752753
return {
753754
x: point.pageX - this._scrollPosition.left,

0 commit comments

Comments
 (0)