Angular切换章节时Dragula重复创建组报错问题求助
解决Angular Dragula重复创建组报错问题
问题分析
你遇到的错误是因为每次点击显示章节时,都会调用createGroup创建同名的Dragula组,但之前创建的组未被销毁,导致重复创建触发报错。
解决方案
核心思路是在章节隐藏时销毁对应Dragula组,显示时再创建,同时在组件销毁时清理所有残留组,避免内存泄漏。
1. 修改章节切换方法,添加组的销毁与创建逻辑
更新toggle方法,在章节状态切换时处理Dragula组:
toggle(item, i) { // 若当前章节即将隐藏,先销毁对应的Dragula组 if (item.shown) { this.dragulaService.destroy(`lectures-list${item.id}`); } item.shown = !item.shown; this.current = i; // 若章节即将显示,重新创建Dragula组 if (item.shown) { this.dragulaService.createGroup(`lectures-list${item.id}`, { moves: function (el, container, handle) { return !handle.classList.contains('edit-mode'); } }); } }
2. 组件销毁时清理所有组
实现OnDestroy生命周期钩子,在组件销毁时销毁所有章节对应的Dragula组:
import { Component, OnDestroy } from '@angular/core'; // ...其他导入 export class YourComponent implements OnDestroy { // ...组件其他代码 ngOnDestroy() { // 遍历所有章节,销毁对应的Dragula组 this.chapters.forEach(chapter => { this.dragulaService.destroy(`lectures-list${chapter.id}`); }); } }
3. 配合视图渲染逻辑优化(可选)
如果你的章节课时列表是通过*ngIf控制显示隐藏的,确保只有当章节shown为true时才渲染对应的<ul>:
<ul *ngIf="item.shown" [ngClass]="canDrag?'':'edit-mode'" class="list-group" [(dragulaModel)]="courseLecturesForm.value.lectures" dragula="lectures-list{{item.id}}" id="lectures-list{{item.id}}"> <li [ngClass]="canDrag?'':'edit-mode'" class="list-group-item draggable array-card-header" formArrayName="lectures" *ngFor="let lecture of courseLecturesForm.get('lectures')['controls']; let i = index;"> <!-- 课时内容 --> </li> </ul>
这样能确保DOM元素和Dragula组的生命周期同步,减少不必要的组创建。
内容的提问来源于stack exchange,提问作者Ismail Muhammad
相关产品推荐
相关产品推荐

