【问题标题】:Angular Material drag n drop CDK remove element on listAngular Material 拖放 CDK 删除列表中的元素
【发布时间】:2020-02-13 08:02:08
【问题描述】:

如何删除列表项?我尝试从与列表关联的数组中删除该项目,但这完全破坏了列表。

我使用 Angular (with Material) 9.0

【问题讨论】:

  • 请为它添加一个堆栈闪电战。
  • 在 drop 函数中,你有 event 作为参数。这里有属性:container、previousContainer、index、previousIndex,参见material.angular.io/cdk/drag-drop/api#CdkDragDrop。你需要创建一个splice(previousContainer.data,previousIndex,1) 或类似的 - 不要使用函数 transferArrayItem-
  • @Eliseo 谢谢,它的工作非常好!我尝试使用 slice,但它不能正常工作,显然是由于数组替换。
  • @VasiliMaslov,这个想法是使用“事件”参数中的数据。为了让事情变得简单,Angular 给了我们函数 transferArray。如果你好奇,可以在 github 中查看:github.com/angular/components/blob/master/src/cdk/drag-drop/…。你看它只是一个函数。我们可以使用或不使用此功能,当使用拖放时,我们正在使用 cdkDropList,我们使用拖动来管理数组(重新排序,交换两个不同数组的两个元素,...)。完成拖动后,使用这些数组重新绘制组件
  • 请显示代码以便对其他人有所帮助,如果您找到了解决方案,请回答问题。谢谢!

标签: angular angular-material


【解决方案1】:

我有 2 个列表。当我将一个项目从第一个列表 (sequenceOfSlides) 拖动到第二个列表 (listOfSlides) 时,我将其删除,然后从第二个列表复制到第一个列表。问题是我从与列表关联的数组中删除了完全替换的元素。使用@Eliseo,我开始从原始数组中删除元素,而不更改指向它的链接。 模板:

<div class="row" cdkDropListGroup>
        <div class="col-6">
            <div
                    id="sequenceOfSlidesElement"
                    cdkDropList
                    [cdkDropListData]="sequenceOfSlides"
                    class="example-list"
                    (cdkDropListDropped)="drop($event)">
                <div
                        class="example-box"
                        *ngFor="let item of sequenceOfSlides"
                        cdkDrag>
                    {{item.ruName}}
                </div>
            </div>
        </div>

        <div class="col-6">
            <div
                    id="listOfSlidesElement"
                    cdkDropList
                    [cdkDropListEnterPredicate]="noReturnPredicate"
                    [cdkDropListData]="listOfSlides"
                    class="example-list"
                    (cdkDropListDropped)="drop($event)">
                <div
                        class="example-box"
                        *ngFor="let item of listOfSlides"
                        cdkDrag>
                    {{item.ruName}}
                </div>
            </div>
        </div>
    </div>

组件:

 drop(event: CdkDragDrop<ISlide[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      if (event.container.id === 'sequenceOfSlidesElement') {
        copyArrayItem(event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex);
      } else {
        this.sequenceOfSlides.splice(event.previousIndex, 1);
      }
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 2020-09-29
    • 1970-01-01
    • 2019-09-09
    • 2019-04-24
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多