Angular 角度拖放绝对位置元素选择错误索引

Angular 角度拖放绝对位置元素选择错误索引,angular,angular-cdk-drag-drop,Angular,Angular Cdk Drag Drop,我试图在两个列表中拖动项目。底部的列表是一个典型的排序列表(如“库存”),但我希望顶部的项目不排序,可以放在任何地方(如“游戏板”) 我有它的大部分工作,但当下降到顶框事件。currentIndex总是0。但是当从那里拖出时,我会得到不同的event.previousIndex值,这意味着模型和DOM元素并不总是匹配的 这是我的意思。将一些项目拖到顶部框中,并对其进行操作,您会注意到有时会移动错误的项目 最值得注意的是,当您以相反的顺序进行交互时,例如: 将项目“一”、“二”、“三”拖到顶部框中

我试图在两个列表中拖动项目。底部的列表是一个典型的排序列表(如“库存”),但我希望顶部的项目不排序,可以放在任何地方(如“游戏板”)

我有它的大部分工作,但当下降到顶框事件。currentIndex总是0。但是当从那里拖出时,我会得到不同的event.previousIndex值,这意味着模型和DOM元素并不总是匹配的

这是我的意思。将一些项目拖到顶部框中,并对其进行操作,您会注意到有时会移动错误的项目

最值得注意的是,当您以相反的顺序进行交互时,例如:

  • 将项目“一”、“二”、“三”拖到顶部框中(按该顺序)
  • 尝试将项目“三”、“二”、“一”放回底部框中(按该顺序)

  • cdkDropListSortingDisabled
    选项仅在同一容器内移动项目时有效。如果从一个容器移动到另一个容器,则块的角度位置:

    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
      );
    }
    

    即使不在两个列表之间拖动,问题仍然存在。在分叉版本中,添加所有三项,然后在该组中移动它们。你会注意到,由于索引错误,不时会有一块跳转。(非常感谢你的帮助)我忘了检查同一组。你能再测试一下吗?天哪,你解决了!好几天来我一直在想这个,泰姆!!如果在同一高度(即顶部)有两个不重叠的元素,这将如何工作?似乎应该有一个二级排序…如果你想,你也可以应用这个二级排序