3

我正在尝试将项目拖到两个列表中。底部列表是典型的排序列表(如“库存”),但我希望顶部项目未排序且可放置在任何地方(如“游戏板”)。

我让它大部分工作,但是当放入顶部框时 event.currentIndex 始终为 0。但是当从那里拖出时,我得到不同的 event.previousIndex 值,这意味着模型和 DOM 元素并不总是匹配。

这是一个堆栈闪电战,显示了我的意思。将一些项目拖到顶部框中并使用它,您会注意到有时移动了错误的项目。

当您以相反的顺序进行交互时,这一点最为显着,例如:

  1. 将项目“一”、“二”、“三”拖到顶部框中(按此顺序)
  2. 尝试将项目“三”、“二”、“一”放回底部盒子(按此顺序)

在此处输入图像描述

4

1 回答 1

1

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

于 2020-05-03T19:06:44.613 回答