https://stackblitz.com/edit/angular-zscthy?file=src%2Fapp%2Fapp.component.ts
将项目从容器拖放到另一个容器后,您需要更新原始 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(添加代码以在用户将项目从容器移动到另一个容器时删除 a/b 对象中的项目)
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);
}
}