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

谁都会走 提交于 2019-12-10 03:44:06

问题


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

The documentation deals with rearranging items within lists or transferring items between several lists. However, it doesn't talk about tables.

I was wondering whether there is a comfortable way of using angular material's drag-and-drop system for reordering rows in mat-table or cdk-table.

(You can add cdkDropList to mat-table which makes the mechanism work but without all the fancy animations and default drag placeholders.)

Does something like an easy-to-implement default for sorting table rows via drag-and-drop exist?


回答1:


The styling is done by CSS (look at the CSS tab on the example page). I tweaked it to work with mat-table:

.cdk-drag-preview {
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
              0 8px 10px 1px rgba(0, 0, 0, 0.14),
              0 3px 14px 2px rgba(0, 0, 0, 0.12);
}

.cdk-drag-placeholder {
  opacity: 0;
}

.cdk-drag-animating {
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}

.cdk-drop-list-dragging .mat-row:not(.cdk-drag-placeholder) {
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}

I placed this in my main styles.scss file.


For anyone wondering how to implement drag and drop on a mat-table, you need to:

  1. Add cdkDropList to mat-table
  2. Add (cdkDropListDropped)="onListDrop($event)" to mat-table
  3. Add cdkDrag to mat-row

onListDrop will look something like:

onListDrop(event: CdkDragDrop<string[]>) {
  // Swap the elements around
  moveItemInArray(this.myArray, event.previousIndex, event.currentIndex);
}

moveItemInArray is an Angular Material function. You can import it.




回答2:


Found example https://stackblitz.com/edit/angular-igmugp

Looks the missing part is

this.table.renderRows();



回答3:


I found a very good example on stackblitz: https://stackblitz.com/edit/table-drag-n-drop

To not break the ui of the Drag&Drop preview, use the tags

<mat-table>...</mat-table>
<mat-header-cell>...</mat-header-cell>
<mat-cell>...</mat-cell>
<mat-header-row>...</mat-header-row>
<mat-row>...</mat-row>

instead of

<table mat-table>...</table mat-table>
<th mat-header-cell>...</th mat-header-cell>
<td mat-cell>...</td mat-cell>
<tr mat-header-row>...</tr mat-header-row>
<tr mat-row>...</tr mat-row>

Combined with the css mentioned in https://stackoverflow.com/a/53630171/12331146 it is the perfect solution for me.



来源:https://stackoverflow.com/questions/53377450/reorder-mat-table-rows-with-angular-materials-drag-and-drop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!