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

Angular Material 14拖拽:如何从drop事件获取父容器对象?

解决方案

可以通过调整cdkDropListData的绑定逻辑,直接从拖拽事件中获取完整的父容器对象,具体实现如下:

1. 修改模板数据绑定

将cdkDropListData从绑定父容器的children数组改为绑定整个父对象,这样拖拽触发时事件就能携带父容器的完整信息:

<!-- Parent Container -->
<div class="parent-container"
    [id]="articleDropListId + i"
    cdkDropList
    [cdkDropListData]="parent" <!-- 绑定完整的父对象 -->
    (cdkDropListDropped)="drop($event)">

    <!-- Children -->
    <div class="children" *ngFor="let child of parent.children" cdkDrag>
        <!-- Child -->
        <div class="child">
            {{child.name}}
        </div>
    </div>
</div>

2. 更新drop函数逻辑

现在event.container.data就是完整的父容器对象,只需调整数组操作的参数(指向父对象的children属性),即可直接获取父容器名称:

public drop(event: CdkDragDrop<any>): void { // 泛型可替换为自定义的ParentModel类型
    // 直接从事件中获取目标父容器对象
    const targetParent = event.container.data;
    const targetParentName = targetParent.name;

    if (event.previousContainer !== event.container) {
        // 跨容器转移:操作父对象的children数组
        transferArrayItem(
            event.previousContainer.data.children,
            event.container.data.children,
            event.previousIndex,
            event.currentIndex
        );
        const movedChild: ChildModel = event.container.data.children[event.currentIndex];
        // 可选:更新子项的parentName,保持数据一致性
        movedChild.parentName = targetParentName;
        this.apiService.moveChild(movedChild, targetParentName);
    } else {
        // 同容器排序:同样操作children数组
        moveItemInArray(
            event.container.data.children,
            event.previousIndex,
            event.currentIndex
        );
        const movedChild: ChildModel = event.container.data.children[event.currentIndex];
        this.apiService.moveChild(movedChild, targetParentName);
    }
}

核心说明

  • 绑定完整父对象到cdkDropListData是关键,避免了额外的查找逻辑,直接从事件中获取父容器信息。
  • 数组操作时必须明确指向父对象的children属性,确保拖拽排序/转移逻辑正常运行。
  • 移动子项后更新其parentName属性,能保证前端数据与服务器端同步(可选但推荐)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:55:24