Duplicate items in angular material drag and drop

2.3k views Asked by At

is there some way in angular material to prevent duplicate items in drop list? here is example code

https://stackblitz.com/edit/angular-xjex4y-43l7uh

I try to check if the item already exists in an array with event.currentIndex but this is not correct, because, sometimes I get the wrong value.

event.container.data.included(event.container.data[event.currentIndex])

In stackblitz i need to use .indexOf() insead od .included(), because something not working

2

There are 2 answers

5
jitender On BEST ANSWER

You can check current item using previousIndex and check if item already exist or not if exist then return like

 {
      let idx=event.container.data.indexOf(event.previousContainer.data[event.previousIndex]);
      if(idx != -1){
        return;//if item exist
      }
      copyArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
    }

working demo

0
Eliseo On

about your question to remove the element when drag outside you can use the "Output" cdkDragDropped. The event return an object of type CdkDragDrop that have a property isPointerOverContainer. When this property is false you drop the item "outside" the cdk-drop-list.

<div class="example-box" *ngFor="let item of done" cdkDrag 
        (cdkDragDropped)="dropped($event)" >{{item}}</div>

  dropped(event:any){
    if (!event.isPointerOverContainer)
      event.previousContainer.data.splice(event.previousIndex,1)
  }

Well, a brief explanation about cdk-drop-list:

A cdk-drop-list it's only a "mechanic" to change in general two arrays (really you can "transport" any data). You can add/remove elements to one or to another one array, you can interchange elements in the arrays or whatever.

  1. A cdk-drop-list has a "data": generally an array but can be any object
  2. Inside the each cdk-drop-list we have one or more cdk-drag: elements that we can drag.
  3. a cdk-droplist have events that we can "capture": e.g. cdkDropListDropped
  4. a cdk-drag also have events that we can "capture": e.g. cdkDragDropped
  5. In this events the argument (see the type) is an object with properties. A lot of this object have a property the cdk-drop-list from and to drag/drop : "container" and "previousContainer" (so we can get the "data" using "container.data" and "previousContainer.data) and the index. So we can get the element that is dragged previousContainer.data[previousIndex] and the position where is dropped.

You can do anything with this elements