Angular 14嵌套章节拖拽问题:子章节无法跨章节移动求助
解决Angular CDK子章节跨章节拖拽问题
问题原因
你当前的子章节跨章节拖拽失败,核心问题有两个:
- 原章节查找逻辑不可靠:用
sec.subsections === event.previousContainer.data做引用相等判断,若数组在生命周期中被重新赋值(比如接口更新、深拷贝),引用会不一致,导致找不到原章节。 - 数据关联未更新:跨章节移动后,子章节及其内部
lecture/assignment的section字段仍绑定旧章节ID,会造成数据不一致。
解决方案
- 通过容器ID定位原章节:利用你给子章节DropList设置的
id="sec"+i,提取索引直接从demoData中获取原章节,规避引用比较的问题。 - 更新子章节关联字段:移动完成后,将子章节及其内部的
section字段替换为目标章节ID,保证数据一致性。
修改后的代码
TypeScript部分
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop'; // ... dropSubsection(event: CdkDragDrop<any[]>, targetSection: any) { if (event.previousContainer === event.container) { // 同一章节内移动 moveItemInArray(targetSection.subsections, event.previousIndex, event.currentIndex); } else { // 跨章节移动:通过容器ID提取原章节索引 const prevContainerIndex = parseInt(event.previousContainer.id.replace('sec', ''), 10); const sourceSection = this.demoData[prevContainerIndex]; if (sourceSection) { // 转移子章节数组项 transferArrayItem( sourceSection.subsections, targetSection.subsections, event.previousIndex, event.currentIndex ); // 更新子章节的关联字段 const movedSubsection = targetSection.subsections[event.currentIndex]; movedSubsection.section = targetSection.id; if (movedSubsection.type === 'lecture') { movedSubsection.lecture.section = targetSection.id; } else if (movedSubsection.type === 'assignment') { movedSubsection.assignment.section = targetSection.id; } } else { console.error('原章节未找到'); } } }
HTML部分(仅调整参数命名更清晰,逻辑无改动)
<div cdkDropListGroup> <div cdkDropList [cdkDropListData]="demoData" (cdkDropListDropped)="dropSection($event)" class="section-list"> <div *ngFor="let section of demoData; let i = index" class="section" cdkDrag> <h2>{{ section.title }}</h2> <div cdkDropList [id]="'sec'+i" [cdkDropListData]="section.subsections" class="subsection-list" (cdkDropListDropped)="dropSubsection($event, section)"> <div *ngFor="let subsection of section.subsections" class="subsection-item" cdkDrag> <div *ngIf="subsection.type === 'lecture'">{{ subsection.lecture?.title }}</div> <div *ngIf="subsection.type === 'assignment'">{{ subsection.assignment?.title }}</div> </div> </div> </div> </div> </div>
说明
- 容器ID索引的方式比引用比较更稳定,只要ID和章节索引绑定,就能准确找到原章节。
- 更新关联字段后,后续保存到后端或其他数据操作时,子章节会正确关联目标章节。
内容的提问来源于stack exchange,提问作者Al Imran
相关产品推荐
相关产品推荐

