Search code examples
angularangular-materialangular-material-7

cdkDropList doesn't save new order of items


I have a super simple drop list in my angular project:

<ul cdkDropList style="padding: 20px;">
    <li cdkDrag>111111</li>
    <li cdkDrag>222222</li>
    <li cdkDrag>333333</li>
    <li cdkDrag>444444</li>
    <li cdkDrag>555555</li>
</ul>

However, when I drag 111111 to the end, it jumps back to being first in the list.


Solution

  • You are missing a data source.

    After Dragging, you must update that data source to reflect your UI.

    It is jumping back to your real modal state.

    Example:

    HTML:

    <div class="box-list" cdkDropList (cdkDropListDropped)="drop($event)">
      <div class="drag-box" *ngFor="let customer of customers" cdkDrag>
        {{customer.name}}
      </div>
    </div>
    

    TS file:

    import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
    ...
    export class SortListComponent implements OnInit {
      customers = [
        { name: 'Adam', age: 23 },
        { name: 'Jack', age: 27 },
        { name: 'Katherin', age: 26 },
        { name: 'John', age: 30 },
        { name: 'Watson', age: 42 },
      ];
    
      drop(event: CdkDragDrop<string[]>) {
        moveItemInArray(this.customers, event.previousIndex, event.currentIndex);
      }
    }
    

    Notice my customers is my data source. And I am updating it after drop