尝试清除Angular 8 CDK拖放列表

时间:2019-09-16 01:27:55

标签: angular angular-cdk

我正在使用Angular创建一个简单的拖放列表,无法弄清楚如何将表重置为其开始安排。我试图使用transferArrayItem,但是我不知道如何引用该表来访问列表中的项目。

<div class="container">
<h2>Groceries</h2>

<div cdkDropList #todoList="cdkDropList" [cdkDropListData]="todo"
  [cdkDropListConnectedTo]="doneList" class="list" (cdkDropListDropped)="drop($event)">
<div class="list-item" *ngFor="let item of todo" cdkDrag>{{item}}</div>
</div>
</div>

<div class="container">
<h2>Cart</h2>

<div cdkDropList #doneList="cdkDropList" [cdkDropListData]="done"
 [cdkDropListConnectedTo]="todoList" class="list" (cdkDropListDropped)="drop($event)">
<div class="list-item" *ngFor="let item of done" cdkDrag>{{item}}</div>
</div>
</div>

<div id="buttons">
<button id="clearCart" (click)="clearCart()">Clear Cart</button>
<button id="checkout" (click)="checkout()">Checkout</button>
</div>

这是我的“ groceries.component.html”文件,在其中找到并定义了列表。下面是运行这些函数的“ groceries.component.ts”文件。

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
selector: 'app-groceries',
templateUrl: './groceries.component.html',
styleUrls: ['./groceries.component.css'],
})
export class GroceriesComponent {
todo = [
'Apple',
'Banana',
'Avocado',
'Cheez-Its',
'Doritos',
'Gushers',
'Orange',
'Big ol steaks'
];

done = [
];

drop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
  moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
  transferArrayItem(event.previousContainer.data,
      event.container.data,
      event.previousIndex,
      event.currentIndex);
}
}

clearCart(){


window.alert("Cart has been cleared!");
}

exit(){

}

checkout(){
window.alert("Don't worry about paying, we'll ship them right now!");
}
}

我本打算使用exit()方法将元素重置回原始位置,但仍然遇到不知道如何访问“完成”数组中各项信息的问题。

另外,值得注意的是,我是第一次探索Angular,“ todo”和“ done”列表是自动生成的,并且我计划在功能正常工作时更改名称。

1 个答案:

答案 0 :(得分:0)

  exit() {
    this.todo = [...this.todo, ...this.done];
    this.done = [];
  }

https://stackblitz.com/edit/angular-avfyze?file=app/cdk-drag-drop-connected-sorting-example.ts