Skip to content

Commit 77029e9

Browse files
committed
refactor(drag-drop): expose method for resetting the drag position
Exposes an API that allows people to reset the position of a `cdkDrag`. Fixes #13661.
1 parent 6c741c4 commit 77029e9

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,6 +427,33 @@ describe('CdkDrag', () => {
427427
expect(event.stopPropagation).toHaveBeenCalled();
428428
}));
429429

430+
it('should be able to reset a freely-dragged item to its initial position', fakeAsync(() => {
431+
const fixture = createComponent(StandaloneDraggable);
432+
fixture.detectChanges();
433+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
434+
435+
expect(dragElement.style.transform).toBeFalsy();
436+
dragElementViaMouse(fixture, dragElement, 50, 100);
437+
expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)');
438+
439+
fixture.componentInstance.dragInstance.reset();
440+
expect(dragElement.style.transform).toBeFalsy();
441+
}));
442+
443+
it('should start dragging an item from its initial position after a reset', fakeAsync(() => {
444+
const fixture = createComponent(StandaloneDraggable);
445+
fixture.detectChanges();
446+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
447+
448+
expect(dragElement.style.transform).toBeFalsy();
449+
dragElementViaMouse(fixture, dragElement, 50, 100);
450+
expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)');
451+
fixture.componentInstance.dragInstance.reset();
452+
453+
dragElementViaMouse(fixture, dragElement, 25, 50);
454+
expect(dragElement.style.transform).toBe('translate3d(25px, 50px, 0px)');
455+
}));
456+
430457
});
431458

432459
describe('draggable with a handle', () => {

src/cdk/drag-drop/drag.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,13 @@ export class CdkDrag<T = any> implements AfterViewInit, OnDestroy {
260260
return this._rootElement;
261261
}
262262

263+
/** Resets a standalone drag item to its initial position. */
264+
reset(): void {
265+
this._rootElement.style.transform = '';
266+
this._activeTransform = {x: 0, y: 0};
267+
this._passiveTransform = {x: 0, y: 0};
268+
}
269+
263270
ngAfterViewInit() {
264271
// We need to wait for the zone to stabilize, in order for the reference
265272
// element to be in the proper place in the DOM. This is mostly relevant

0 commit comments

Comments
 (0)