簡體   English   中英

角材料拖放:自定義管道問題

[英]Angular Material Drag & Drop : Custom Pipe Issue

我正在使用 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's Documentation 中為拖放事件提供的示例

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),當我拖放寵物時,錯誤的寵物被放入框中(實際上它是位於索引 0 但被隱藏的“Stella”)並且 Rex 仍然出現在寵物清單。

我希望我的解釋清楚(對不起我的英語),但你可以在上面提到的這個 stackblitz 上嘗試:如果你過濾寵物並進行拖放,錯誤的寵物會被移動。

這個 gif 說明了這個問題:

在此處輸入圖片說明

似乎 drop 事件采用了未過濾列表的索引,我不知道如何修復它。

非常感謝。

您好,我遇到了同樣的問題並做了很多研究,我已經實現了這一點,在這種情況下,可以使用該卡上的touchend事件和mousedown事件並傳遞當前項目和數組

以下代碼用於移動觸摸屏touchend

<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>

聲明一個變量

 previousIndex:number;

所以在該組件的 ts 文件中添加這個

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

現在用this.previousIndex替換event.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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM