Skip to content

Commit ba31c72

Browse files
crisbetovivian-hu-zz
authored andcommitted
refactor(drag-drop): expose method for resetting the drag position (#13673)
Exposes an API that allows people to reset the position of a `cdkDrag`. Fixes #13661.
1 parent 95a1abe commit ba31c72

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,32 @@ describe('CdkDrag', () => {
442442
expect(dragElement.style.touchAction)
443443
.not.toEqual('none', 'should not disable touchAction on when there is a drag handle');
444444
});
445+
it('should be able to reset a freely-dragged item to its initial position', fakeAsync(() => {
446+
const fixture = createComponent(StandaloneDraggable);
447+
fixture.detectChanges();
448+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
449+
450+
expect(dragElement.style.transform).toBeFalsy();
451+
dragElementViaMouse(fixture, dragElement, 50, 100);
452+
expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)');
453+
454+
fixture.componentInstance.dragInstance.reset();
455+
expect(dragElement.style.transform).toBeFalsy();
456+
}));
457+
458+
it('should start dragging an item from its initial position after a reset', fakeAsync(() => {
459+
const fixture = createComponent(StandaloneDraggable);
460+
fixture.detectChanges();
461+
const dragElement = fixture.componentInstance.dragElement.nativeElement;
462+
463+
expect(dragElement.style.transform).toBeFalsy();
464+
dragElementViaMouse(fixture, dragElement, 50, 100);
465+
expect(dragElement.style.transform).toBe('translate3d(50px, 100px, 0px)');
466+
fixture.componentInstance.dragInstance.reset();
467+
468+
dragElementViaMouse(fixture, dragElement, 25, 50);
469+
expect(dragElement.style.transform).toBe('translate3d(25px, 50px, 0px)');
470+
}));
445471

446472
});
447473

src/cdk/drag-drop/drag.ts

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

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

0 commit comments

Comments
 (0)