用滤镜拖放



我有一个Angular应用程序。它包含两个工作正常的拖放列表。我想添加一个过滤器来搜索列表中的项目。问题是当我过滤项目时,函数transferArrayItem将使用错误的索引,这就是为什么它会移动错误的项目。
我添加了一个stackblitz代码来显示这个问题。要重现此问题,请遵循以下步骤:

  1. 在第一个列表上单击搜索并键入数字2
  2. 尝试将项目移动到第二个列表,它将移动项目1。

https://stackblitz.com/edit/angular-mwnmo5?file=src%2Fapp%2Fapp.component.ts

我终于找到了用最干净的代码解决问题的方法。我使用cdkDropList的id来了解源列表,然后我手动转移项目,而不是使用cdkDragDrop提供的transferArrayItem函数。

完整的代码在
https://stackblitz.com/edit/angular-htpgvx?file=src%2Fapp%2Fapp.component.ts

https://stackblitz.com/edit/angular-zscthy?file=src%2Fapp%2Fapp.component.ts

在将item从容器放入另一个容器后,需要更新原来的a/b对象因此,使用搜索框组件是不可能做到这一点的。

app.component.html,我添加了<input>,删除了<app-search-box>,添加了id到<div cdkDropList>

<input
#search_a
type="text"
class="form-control"
placeholder="Search"
aria-label="Search"
aria-describedby="basic-addon1"
/>
<div
cdkDropList
[cdkDropListData]="selectedList"
class="example-list"
(cdkDropListDropped)="dropItem($event)"
id="a_drop_list"
>

app.component.ts,我添加了代码来监听输入keydown事件

fromEvent(this.search_a.nativeElement, 'keydown')
.pipe(
debounceTime(550),
map(x => x['target']['value'])
)
.subscribe(value => {
this.updateFilter_a(value);
})

增加了updateFilter功能,当输入keydown时触发

updateFilter_a(val: any) {
this.selectedList = [];
this.selectedList = a.filter(v => v.title.indexOf(val)>= 0 || v.description.indexOf(val) >= 0);
}

修改了dropItem(增加了当用户将item从容器移动到另一个容器时删除item的代码)

dropItem(event: CdkDragDrop<any[]>) {
if (event.previousContainer !== event.container) {
transferArrayItem(
event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex
);
//dropped item id
const delete_id = event.container.data[event.currentIndex].id;
//item drop to a_drop_list
if(event.container.id === 'a_drop_list') {
//find object b item index when id == device_id
var index = b.findIndex(function(o){
return o.id === delete_id;
})
//delete item match id == device_id in obejct b
if (index !== -1) b.splice(index, 1);
} else if(event.container.id === 'b_drop_list') {
var index = a.findIndex(function(o){
return o.id === delete_id;
})
if (index !== -1) a.splice(index, 1);
}
}

最新更新