如何解决从下拉列表中删除最新项目
我正在研究角度拖放。我的代码如下
我正在删除的项目将始终删除在完成列表的末尾。我想在最新删除的项目上有一个“X”标记(假设用户拖放 item1 然后“X”应该在 items1 上,如果用户拖放 item2 那么“X”应该只在 item2 上),以便如果用户愿意用户可以点击“X”,项目从完成列表中删除并再次返回到“待办事项”列表。
解决方法
我已经进行了更改。所以我在这里粘贴 HTML 和 TS 代码。我不确定代码是否保存在 stackblitz 中。
在组件文件 cdk-drag-drop-connected-sorting-example.ts
中:
import { Component,OnInit } from "@angular/core";
import {
CdkDragDrop,moveItemInArray,transferArrayItem
} from "@angular/cdk/drag-drop";
/**
* @title Drag&Drop connected sorting
*/
@Component({
selector: "cdk-drag-drop-connected-sorting-example",templateUrl: "cdk-drag-drop-connected-sorting-example.html",styleUrls: ["cdk-drag-drop-connected-sorting-example.css"]
})
export class CdkDragDropConnectedSortingExample implements OnInit{
todo = [
"Get to work","Pick up groceries","Go home","Fall asleep","Walk Dog","Stretch","Code Stuff","Drag Stuff","Drop Stuff","Run","Walk"
];
done = ["Get up","Brush teeth","Take a shower","Check e-mail","Walk dog"];
public DroppedListLength; // tracking the length of the list
ngOnInit() {
this.DroppedListLength = this.done.length;
}
drop(event: CdkDragDrop<string[]>) {
if (event.previousContainer === event.container) {
console.log("first if..");
moveItemInArray(
event.container.data,event.previousIndex,event.currentIndex
);
} else {
transferArrayItem(
event.previousContainer.data,event.container.data,this.done.length
);
console.log("second if..");
this.DroppedListLength = this.done.length; // update the list length for any drop
}
}
// just add a function to remove the last added value
removeLastDroppedItem() {
this.done.pop();
this.DroppedListLength = this.done.length; // you can add this to keep track of last item in the list
}
}
在 html cdk-drag-drop-connected-sorting-example.html
中,您只需要添加一个按钮并将其点击与上述功能相关联:
<div class="example-container">
<h2>To do</h2>
<div cdkDropList #todoList="cdkDropList" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[doneList]" class="example-list"
(cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of todo" cdkDrag>{{item}}</div>
</div>
</div>
<br>
<div class="example-container">
<h2>Done</h2>
<div cdkDropList #doneList="cdkDropList" [cdkDropListData]="done" [cdkDropListConnectedTo]="[todoList]" class="example-list"
(cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let item of done; let i = index" cdkDrag>{{item}}
<span *ngIf="i+1 === DroppedListLength" (click)="removeLastDroppedItem()">X</span></div>
</div>
</div>
注意:您可以更新这些文件,它应该会按预期工作。
,目标是存储最后一个元素的索引,然后在模板中应用逻辑 Solution
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。