From 2886f749147aa5913c07a1db31636b5444372c8d Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Thu, 24 Jul 2025 10:21:37 +0200 Subject: [PATCH] fix(cdk/drag-drop): incorrect index when returning item in mixed list 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. --- src/cdk/drag-drop/sorting/mixed-sort-strategy.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts b/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts index f5cb575d8686..d863fec910d6 100644 --- a/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts +++ b/src/cdk/drag-drop/sorting/mixed-sort-strategy.ts @@ -141,6 +141,14 @@ export class MixedSortStrategy implements DropListSortStrategy { * out automatically. */ enter(item: DragRef, pointerX: number, pointerY: number, index?: number): void { + // Remove the item from current set of items first so that it doesn't throw off the indexes + // further down in this method. See https://github.com/angular/components/issues/31505 + const currentIndex = this._activeItems.indexOf(item); + + if (currentIndex > -1) { + this._activeItems.splice(currentIndex, 1); + } + let enterIndex = index == null || index < 0 ? this._getItemIndexFromPointerPosition(item, pointerX, pointerY) @@ -154,11 +162,6 @@ export class MixedSortStrategy implements DropListSortStrategy { } const targetItem = this._activeItems[enterIndex] as DragRef | undefined; - const currentIndex = this._activeItems.indexOf(item); - - if (currentIndex > -1) { - this._activeItems.splice(currentIndex, 1); - } if (targetItem && !this._dragDropRegistry.isDragging(targetItem)) { this._activeItems.splice(enterIndex, 0, item);