cdkDropListSortingDisabled
选项仅在同一容器内移动项目时有效。如果你从一个容器移动到另一个容器,那么 Angular 会对块的位置进行排序:
this._itemPositions = this._activeDraggables.map(drag => {
const elementToMeasure = drag.getVisibleElement();
return {drag, offset: 0, clientRect: getMutableClientRect(elementToMeasure)};
}).sort((a, b) => {
return isHorizontal ? a.clientRect.left - b.clientRect.left :
a.clientRect.top - b.clientRect.top;
});
由于您没有提供方向并且默认为垂直,因此它按top
位置排序。
顶部框event.currentIndex
始终为 0,因为您使用绝对定位并且占位符始终位于顶部。
尝试添加以下样式以查看占位符的显示位置:
.cdk-drag-placeholder {
opacity: 1;
background: red;
}
要修复它,您可以currentIndex
自己计算,例如:
const isWithinSameContainer = event.previousContainer === event.container;
let toIndex = event.currentIndex;
if (event.container.sortingDisabled) {
const arr = event.container.data.sort((a, b) => a.top - b.top);
const targetIndex = arr.findIndex(item => item.top > top);
toIndex =
targetIndex === -1
? isWithinSameContainer
? arr.length - 1
: arr.length
: targetIndex;
}
const item = event.previousContainer.data[event.previousIndex];
item.top = top;
item.left = left;
if (isWithinSameContainer) {
moveItemInArray(event.container.data, event.previousIndex, toIndex);
} else {
transferArrayItem(
event.previousContainer.data,
event.container.data,
event.previousIndex,
toIndex
);
}
分叉的 Stackblitz