我正在使用 Angular Material Drag And Drop 进行一些项目。 我在 StackBlitz 上做了一个简化的例子 https://stackblitz.com/edit/drag-and-drop-with-pipe?file=src%2Fapp%2Fdispatch.component.ts
宠物列表和盒子列表。 您可以将宠物拖放到盒子列表的一个区域中,这样每个盒子可以包含 X 只宠物。
这行得通! 但我想添加一个自定义管道来动态过滤每个列表,例如只显示猫,或名为 Rex 的宠物
我是 Angular 和 JS/TS 的新手,我找到了这段代码来制作我的自定义管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'listFilter'
})
export class ListFilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if (!items) return [];
if (!searchText) return items;
return items.filter(item => {
return Object.keys(item).some(key => {
return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
});
});
}
}
我还使用 Material 文档中给出的拖放事件示例
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);
}
}
这有效! 但是没有!
没有过滤器,当宠物被放入一个盒子时,它从宠物列表中消失并出现在盒子里。没关系!
但是当我拖放宠物时使用过滤器(例如 Name = Rex,索引为 1),错误的宠物被放入框中(实际上它是索引 0 但隐藏的“Stella”)并且 Rex 仍然出现在宠物列表中。
我希望我的解释很清楚(对不起我的英语),但你可以在上面提到的这个 stackblitz 上试试:如果你过滤宠物并进行拖放,错误的宠物会被移动。
这个 gif 说明了这个问题:
似乎 drop 事件采用了未过滤列表的索引,我不知道如何修复它。
非常感谢。
最佳答案
你好我遇到了同样的问题并做了很多研究并且我已经实现了这个,在这种情况下使用可以在该卡上使用 touchend 事件和 mousedown 事件并传递当前项和数组
以下代码用于手机触摸屏 touchend
<div*ngFor="let item of array">
<div (touchend)="dragTouchEndEvent(array,item)">
</div>
</div>
此代码用于桌面浏览器 (mousedown)
<div*ngFor="let item of array">
<div (mousedown)="dragTouchEndEvent(array,item)">
</div>
</div>
声明一个变量
previousIndex:number;
所以在那个组件的ts文件中添加这个
dragTouchEndEvent(itemArray, item) {
this.previousIndex = itemArray.findIndex(e => e === item);
}
现在将 event.previousIndex 替换为 this.previousIndex 并清除搜索过滤器
someMethod(event: CdkDragDrop<any>){
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, this.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,
event.container.data,
this.previousIndex,
event.currentIndex);
}
//clear your search filter here
}
关于javascript - Angular Material 拖放 : Custom Pipe Issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57818708/