Skip to content

Commit 512066a

Browse files
committed
fix(cdk/drag-drop): incorrect index when returning item in mixed list (#31592)
When an item enters a mixed orientation list, we were figuring out its index, removing the item from the list and then trying to insert it in that index. The problem is that by removing the item, we might have changed the array in a way where the index isn't valid anymore. These changes resolve the issue by removing the item first before making any index calculations. Fixes #31505. (cherry picked from commit 88d4ffd)
1 parent 1db7780 commit 512066a

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/cdk/drag-drop/sorting/mixed-sort-strategy.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,14 @@ export class MixedSortStrategy implements DropListSortStrategy {
141141
* out automatically.
142142
*/
143143
enter(item: DragRef, pointerX: number, pointerY: number, index?: number): void {
144+
// Remove the item from current set of items first so that it doesn't throw off the indexes
145+
// further down in this method. See https://github.com/angular/components/issues/31505
146+
const currentIndex = this._activeItems.indexOf(item);
147+
148+
if (currentIndex > -1) {
149+
this._activeItems.splice(currentIndex, 1);
150+
}
151+
144152
let enterIndex =
145153
index == null || index < 0
146154
? this._getItemIndexFromPointerPosition(item, pointerX, pointerY)
@@ -154,11 +162,6 @@ export class MixedSortStrategy implements DropListSortStrategy {
154162
}
155163

156164
const targetItem = this._activeItems[enterIndex] as DragRef | undefined;
157-
const currentIndex = this._activeItems.indexOf(item);
158-
159-
if (currentIndex > -1) {
160-
this._activeItems.splice(currentIndex, 1);
161-
}
162165

163166
if (targetItem && !this._dragDropRegistry.isDragging(targetItem)) {
164167
this._activeItems.splice(enterIndex, 0, item);

0 commit comments

Comments
 (0)