Skip to content

Commit 24a3f29

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 df9ec74 commit 24a3f29

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,39 @@ describe('CdkDrag', () => {
388388
expect(dragElement.style.transform).toBeFalsy();
389389
}));
390390

391+
it('should be able to reset a freely-dragged item to its initial position', fakeAsync(() => {
392+
const fixture = createComponent(StandaloneDraggable);
393+
fixture.detectChanges();
394+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
395+
396+
expect(dragElement.style.transform).toBeFalsy();
397+
398+
dragElementViaMouse(fixture, dragElement, 50, 100);
399+
expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)');
400+
401+
fixture.componentInstance.dragInstance.reset();
402+
403+
expect(dragElement.style.transform).toBeFalsy();
404+
}));
405+
406+
it('should start dragging an item from its initial position after a reset', fakeAsync(() => {
407+
const fixture = createComponent(StandaloneDraggable);
408+
fixture.detectChanges();
409+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
410+
411+
expect(dragElement.style.transform).toBeFalsy();
412+
413+
dragElementViaMouse(fixture, dragElement, 50, 100);
414+
expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)');
415+
416+
fixture.componentInstance.dragInstance.reset();
417+
418+
expect(dragElement.style.transform).toBeFalsy();
419+
420+
dragElementViaMouse(fixture, dragElement, 25, 50);
421+
expect(dragElement.style.transform).toBe('translate3d(25px, 50px, 0px)');
422+
}));
423+
391424
});
392425

393426
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
@@ -248,6 +248,13 @@ export class CdkDrag<T = any> implements AfterViewInit, OnDestroy {
248248
return this._rootElement;
249249
}
250250

251+
/** Resets a standalone drag item to its initial position. */
252+
reset(): void {
253+
this._rootElement.style.transform = '';
254+
this._activeTransform = {x: 0, y: 0};
255+
this._passiveTransform = {x: 0, y: 0};
256+
}
257+
251258
ngAfterViewInit() {
252259
// We need to wait for the zone to stabilize, in order for the reference
253260
// element to be in the proper place in the DOM. This is mostly relevant

0 commit comments

Comments
 (0)