Home > OS >  how to stop adding an index in a list when droping an element from one list to another using cdkDrag
how to stop adding an index in a list when droping an element from one list to another using cdkDrag

Time:06-23

enter image description here

I am trying to add a row from one list to another list. cdkDragDrop works properly for moving a row in the same list but when i try to move a row from one list to another, a new index is created which I want to avoid.

Refer to the above image

CodePudding user response:

It is unavoidable that new index is created. When you move from one array to another, it needs an index to know location of the item.

And actually, even when you change location of the item within the same list (same array), even then the item index changes and so does every other items that are affected by the change and now due to change of a single item, so have changed other items their index ( 1 / -1).

  todo = ['Get to work', 'Pick up groceries', 'Go home', 'Fall asleep'];

  done = ['Get up', 'Brush teeth', 'Take a shower', 'Check e-mail', 'Walk dog'];

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex); // when change happens in same array (same list)
      this.eventIndex = [event.previousIndex,event.currentIndex];
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex,
      );
      this.eventIndex = [event.previousIndex,event.currentIndex]; // when changes arrays (lists)
    }
  }
    /** Index of the item when it was picked up. */
    previousIndex: number;
    /** Current index of the item. */
    currentIndex: number;
    /** Item that is being dropped. */
    item: CdkDrag<I>;
    /** Container in which the item was dropped. */
    container: CdkDropList<T>;
    /** Container from which the item was picked up. Can be the same as the `container`. */

https://stackblitz.com/edit/angular-mccx4a-b6etwg?file=src/app/cdk-drag-drop-connected-sorting-group-example.ts

  • Related