Skip to content

Commit 1540391

Browse files
crisbetojelbourn
authored andcommitted
fix(drag-drop): return up-to-date position if getFreeDragPosition is called while dragging (#16464)
Currently return the passive position when the consumer calls `getFreeDragPosition`, however the it only gets updated once the user has stopped dragging which means that calling it mid-drag will return incorrect values. These changes make it so the active drag position is returned while dragging.
1 parent d4f2356 commit 1540391

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,27 @@ describe('CdkDrag', () => {
853853
expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100});
854854
}));
855855

856+
it('should be able to get the up-to-date position as the user is dragging', fakeAsync(() => {
857+
const fixture = createComponent(StandaloneDraggable);
858+
fixture.detectChanges();
859+
860+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
861+
const dragInstance = fixture.componentInstance.dragInstance;
862+
863+
expect(dragInstance.getFreeDragPosition()).toEqual({x: 0, y: 0});
864+
865+
startDraggingViaMouse(fixture, dragElement);
866+
dispatchMouseEvent(document, 'mousemove', 50, 100);
867+
fixture.detectChanges();
868+
869+
expect(dragInstance.getFreeDragPosition()).toEqual({x: 50, y: 100});
870+
871+
dispatchMouseEvent(document, 'mousemove', 100, 200);
872+
fixture.detectChanges();
873+
874+
expect(dragInstance.getFreeDragPosition()).toEqual({x: 100, y: 200});
875+
}));
876+
856877
it('should react to changes in the free drag position', fakeAsync(() => {
857878
const fixture = createComponent(StandaloneDraggable);
858879
fixture.componentInstance.freeDragPosition = {x: 50, y: 100};

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,8 @@ export class DragRef<T = any> {
430430
* Gets the current position in pixels the draggable outside of a drop container.
431431
*/
432432
getFreeDragPosition(): Readonly<Point> {
433-
return {x: this._passiveTransform.x, y: this._passiveTransform.y};
433+
const position = this.isDragging() ? this._activeTransform : this._passiveTransform;
434+
return {x: position.x, y: position.y};
434435
}
435436

436437
/**

0 commit comments

Comments
 (0)