You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular CDK拖拽问题:无法获取放置元素ID,onDrop函数失效

Angular CDK拖拽计算功能修复方案

问题说明

要实现拖拽计算功能:将UP(初始值10)拖拽到BH/OT上,拖拽完成后UP变为0,目标项(如BH初始值2)变为两者之和(12)。当前存在的问题是onDrop函数无法触发,无法获取放置目标的ID。

问题根源

当前仅在<tr>上设置了cdkDropList,但放置事件cdkDropListDropped绑定在子元素<td>上,导致事件无法触发——Angular CDK的拖拽放置事件只会绑定在cdkDropList元素本身。

修复代码

修改后的HTML

<table
  class="hoverable child-table"
  style="background-color: white; border-radius: 8px; width: 100%;"
>
  <tr class="container">
    <th style="background-color: rgb(244, 243, 243); max-width: 5%;">MON</th>

    <td
      style="font-family: 'belgrano', sans-serif; max-width: 5%; border-right: 1px solid black;"
    >
      NULL
    </td>

    <!-- BH 作为独立放置容器 -->
    <td
      id="BH"
      cdkDropList
      [cdkDropListData]="'BH'"
      (cdkDropListDropped)="onDrop($event)"
      style="font-family: 'belgrano', sans-serif; max-width: 5%; border-left: 1px solid black;"
    >
      {{ BH }}
    </td>

    <!-- OT 作为独立放置容器 -->
    <td
      id="OT"
      cdkDropList
      [cdkDropListData]="'OT'"
      (cdkDropListDropped)="onDrop($event)"
      style="font-family: 'belgrano', sans-serif; max-width: 5%;"
    >
      {{ OT }}
    </td>

    <td
      id="UP"
      class="draggable"
      style="font-family: 'belgrano', sans-serif; max-width: 5%; border-left: 1px solid black;"
    >
      <span
        cdkDrag
        [cdkDragData]="{ id: 'UP', value: UP }"
        class="column"
      >
        {{ UP }}
      </span>
    </td>
  </tr>
</table>

修改后的TS代码

import { CdkDragDrop } from '@angular/cdk/drag-drop';

// ... 组件其他代码

BH: number = 2;
OT: number = 3;
UP: number = 10;

onDrop(event: CdkDragDrop<any>) {
  // 获取拖拽源数据和目标容器标识
  const dragData = event.item.data;
  const targetId = event.container.data;

  // 仅处理从UP拖到BH/OT的场景
  if (dragData.id === 'UP' && (targetId === 'BH' || targetId === 'OT')) {
    // 将UP的值累加至目标项
    targetId === 'BH' ? this.BH += dragData.value : this.OT += dragData.value;
    // 清空UP的值
    this.UP = 0;
  }
}

关键改动说明

  • 给BH和OT的<td>分别添加cdkDropList属性,通过cdkDropListData传递目标ID,确保放置事件能正确触发
  • 调整cdkDragData为包含ID和值的对象,方便在拖拽事件中识别来源和传递数值
  • 移除原<tr>上的cdkDropList及相关属性,避免事件冲突
  • 在onDrop中直接通过event.container.data获取目标ID,实现数值计算逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:12:48