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

Angular Material Cdk跨列表拖拽如何获取被投放的目标列表项

问题根因

你当前将整个分类列表<mat-list id="category-list">整体设置为了cdkDropList,拖拽投放事件只会识别你将元素放到了这个列表容器内,无法定位到具体的子分类项,所以currentIndex始终为0。

修复方案

调整结构,将每个分类列表项单独设置为可投放的cdkDropList,同时给每个投放目标绑定对应的分类数据,触发投放时直接拿到对应分类即可。

调整后的模板代码

<!-- 产品列表保持基本不变,关联所有分类投放点 -->
<mat-list id="product-list" cdkDropList cdkDropListConnectedTo="category-drop-list">
  <mat-list-item *ngFor="let product of products" cdkDrag [cdkDragData]="product">
      <span>{{product.name}}</span>
  </mat-list-item>
</mat-list>

<!-- 外层分类列表去掉cdkDropList配置 -->
<mat-list id="category-list">
  <!-- 每个分类项单独设为cdkDropList,绑定当前分类数据 -->
  <mat-list-item 
    *ngFor="let category of categories"
    cdkDropList
    id="category-drop-list"
    [cdkDropListData]="category"
    (cdkDropListDropped)="onDrop($event)"
  >
      <span>{{category.name}}</span>
  </mat-list-item>
</mat-list>

onDrop回调处理逻辑

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

onDrop(event: CdkDragDrop<any>) {
  // 拿到被拖拽的产品
  const draggedProduct = event.item.data;
  // 拿到投放目标对应的分类
  const targetCategory = event.container.data;
  
  // 这里执行你的产品归属分类逻辑
  console.log('将产品', draggedProduct.name, '归属到分类', targetCategory.name);
}

该方案兼容Angular/Angular Material 12.1.3版本,无需额外依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:36:05