Search code examples
angulartypescriptdrag-and-dropangular-materialangular-cdk

Drag and drop between several lists


I have 4 lists of four different objects (A, B, C, D).

Is there a way to associate a name with each of these lists? In other words, list A being A, B being B ...

I intend to drag and drop an object and at the same time know which list it came from and where it went.

I used this to find out the automatically generated list value console.log ("FROM" + event.previousContainer.id) console.log ("TO" + event.container.id), the problem is that these values ​​sometimes vary, they are not always the same and if you use conditions it can stop working.

Is there a way to assign or always get the same name from the list where it is object and the one in which it was dropped?

Thanks

Demo- Stackblitz

.ts

  drop(event: CdkDragDrop<string[]>) {
    console.log("FROM" + event.previousContainer.id)
    console.log("TO" + event.container.id)
    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
      );
    }
  }

Solution

  • Inside your drop function call this event data:

    For the previous container:

    event.previousContainer.element.nativeElement.id

    For your current container:

    event.container.element.nativeElement.id


    Then in your HTML add an ID to the list element like that:

    <div ... #activeList="cdkDropList" id="list-A" ...>