Search code examples
angularangular-materialangular7

Angular Material Drag and drop in a table


I have a problem with Angular Material: I need in my Table a drag and drop function but it doesn't work.

this is my component.ts code:

dropTable(event: CdkDragDrop <test[]>) {
  moveItemInArray(this.childTest.data, event.previousIndex, event.currentIndex);
  this.childTestTable.renderRows();
}

Solution

  • Actually updating the data when using the cdkDragDrop on Material Tables is a little wonky, unfortunately. I have created a working poc which you could look at: https://stackblitz.com/edit/table-drag-n-drop

    The important thing is the table data need to be manually updated, here is my drop-function:

      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);
    }
    
    // updates moved data and table, but not dynamic if more dropzones
    this.dataSource.data = clonedeep(this.dataSource.data);
    this.dataSource2.data = clonedeep(this.dataSource2.data);
    }