You need to enable JavaScript to run this app. 如何实现Angular Material列表拖拽元素到容器并保留落点位置
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Angular Material列表拖拽元素到容器并保留落点位置

解决方案

首先你需要放弃Angular CDK DropList的默认自动排序逻辑,改为手动计算拖拽落点坐标,给右侧容器内的元素设置绝对定位来固定位置,具体实现步骤如下:

1. 调整模板结构

<div class="container" cdkDropListGroup>
  <!-- 左侧拖拽源列表 -->
  <div class="list-1" cdkDropList [cdkDropListData]="items" cdkDropListConnectedTo="targetContainer">
    <ul>
      <li cdkDrag *ngFor="let item of items">
        {{item.name}}
        <div class="example-drag" *cdkDragPreview>
          {{item.name}}
        </div>
      </li>
    </ul>
  </div>

  <!-- 右侧目标容器,禁用默认排序逻辑 -->
  <div 
    id="targetContainer"
    class="list-2" 
    cdkDropList 
    [cdkDropListData]="done"
    [cdkDropListSortingDisabled]="true"
    (cdkDropListDropped)="drop($event)"
  >
    <div 
      class="example-drop" 
      cdkDrag 
      cdkDragBoundary=".list-2" 
      *ngFor="let item of done"
      [style.left.px]="item.x"
      [style.top.px]="item.y"
      (cdkDragEnded)="onItemDragEnd($event, item)"
    >
      {{item.name}}
    </div>
  </div>
</div>

2. 补充TS逻辑

首先你的item数据结构需要新增x、y两个字段存储坐标:

interface DragItem {
  name: string;
  x?: number;
  y?: number;
}

// 拖拽释放逻辑
drop(event: CdkDragDrop<DragItem[]>) {
  if (event.previousContainer !== event.container) {
    // 处理从左侧拖入右侧的场景
    const item = event.previousContainer.data[event.previousIndex];
    // 计算落点相对于右侧容器的坐标
    const containerRect = event.container.element.nativeElement.getBoundingClientRect();
    const dropX = event.dropPoint.x - containerRect.left;
    const dropY = event.dropPoint.y - containerRect.top;
    // 给新元素赋值坐标后加入右侧数组
    const newItem = {...item, x: dropX, y: dropY};
    this.done.push(newItem);
    // 从左侧数组移除原元素
    this.items.splice(event.previousIndex, 1);
  }
}

// 右侧已有元素拖拽结束后更新坐标
onItemDragEnd(event: CdkDragEnd, item: DragItem) {
  const { x, y } = event.source.getFreeDragPosition();
  item.x = x;
  item.y = y;
}

3. 补充必要样式

.list-2 {
  position: relative; /* 父容器设为相对定位,子元素绝对定位基于父容器计算 */
  min-height: 400px;
  border: 1px solid #ccc;
}

.example-drop {
  position: absolute; /* 右侧元素设为绝对定位,坐标配置才会生效 */
  cursor: move;
}

以上实现完成后,从左侧拖入右侧的元素会固定在释放时的落点位置,后续拖拽右侧已有元素也会保留新的位置,不会出现自动排序的问题。

内容的提问来源于stack exchange,提问作者r3plica

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 00:15:03