Reorder mat-table rows with angular material's drag-and-drop

后端 未结 5 1346
天涯浪人
天涯浪人 2020-12-29 08:59

Angular 7 brought the powerful DragDropModule with it: https://material.angular.io/cdk/drag-drop/examples

The documentation deals with rearranging items

5条回答
  •  再見小時候
    2020-12-29 09:17

    I was using MatTableDataSource for my dataSource so my solution was this:

    • Importing CdkDragDrop in the component and in the component.module.ts

    • Adding @ViewChild('table') table: MatTable; to the component.ts.

    • In the HTML add:

    • At the *matRowDef you need to add this :

    • Then in the component.ts I made the drop event:

      drop(event: CdkDragDrop) {
        const previousIndex = this.dataSource.data.findIndex(row => row === event.item.data);
        moveItemInArray(this.dataSource.data,previousIndex, event.currentIndex);
        this.dataSource.data = this.dataSource.data.slice();
      }
      
    • 提交回复
      热议问题