角度材质拖放:自定义管道问题

时间:2019-09-06 08:49:43

标签: javascript angular typescript angular-material

我正在使用Angular Material拖放进行一些项目。 我在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());
      });
    });
   }

}

对于拖放事件,我还使用了材料文档中给出的示例

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);
    }
  }


这有效! 但是不!

没有过滤器,将宠物放入盒子时,它会从宠物列表中消失并显示在盒子中。没关系!

但是当我拖放宠物时,使用过滤器(例如,名称= Rex,索引为1),将错误的宠物放到框中(实际上是“ Stella”,它位于索引0,但被隐藏了),而Rex仍然出现在宠物列表中。

我希望我的解释很清楚(对不起我的英语),但是您可以在上面提到的堆叠闪电试验中尝试一下:如果您过滤宠物并进行拖放操作,则会移动错误的宠物。

此gif说明了此问题:

enter image description here

似乎drop事件采用了未过滤列表的索引,我不知道如何解决它。

非常感谢。

1 个答案:

答案 0 :(得分:0)

你好,我遇到了同样的问题,并做了很多研究,并且已经实现了这一点,在这种情况下,使用该卡片时可以使用 touchend 事件和 mousedown 事件并传递当前项目和数组

以下代码用于移动触摸屏 触摸屏

testHarness.processElement2(new StreamRecord<>(element1));
testHarness.processElement1(new StreamRecord<>(new Tuple2<>(id, element2)));

testHarness.setProcessingTime(1); //let's assume it's the correct time for the timer inside the function
softly.assertThat(testHarness.getOutput()).containsExactly(new StreamRecord<>(expectedResult)); // Pass

testHarness.getOutput().clear();

testHarness.setProcessingTime(2); // setting second timer which will trigger different timer
softly.assertThat(testHarness.getOutput()).containsExactly(new StreamRecord<>(expectedResult2)); // Pass

此代码用于桌面浏览器 (鼠标按下)

<div*ngFor="let item of array">
<div (touchend)="dragTouchEndEvent(array,item)">
</div>
</div>

声明一个变量

<div*ngFor="let item of array">
    <div (mousedown)="dragTouchEndEvent(array,item)">
    </div>
    </div>

因此在该组件的ts文件中添加此

 previousIndex:number;

现在用 this.previousIndex 替换 event.previousIndex ,并清除搜索过滤器

 dragTouchEndEvent(itemArray, item) {
    this.previousIndex = itemArray.findIndex(e => e === item);
  }