看起来cdkDragHandle
不适合mat-table
.
使用最新的 Angular Material 版本 v.1 进行了测试9.1.0.
这个错误也在 Github 上进行了讨论,我在那里找到了以下解决方案:https://github.com/angular/components/issues/13770#issuecomment-506182564 https://github.com/angular/components/issues/13770#issuecomment-506182564- 作者ajp76054
.
我在我的项目中使用过它,看起来效果不错。
我将其发布在这里,供有需要的人使用:
初始化表cdkDragDisabled
属性设置为true
,以禁用整个拖动容器。这允许用户仍然与表格单元格交互,直到他们准备好拖动行。
然后在拖动手柄元素上(<mat-icon>
), use (mousedown)
事件来设置cdkDragDisabled
to false
。
然后,将其重置为true
在 - 的里面(cdkDropListDropped)
事件处理程序。
因此,在模板中使用以下代码:
<mat-table
#table
[dataSource]="dataSource"
cdkDropList
(cdkDropListDropped)="drop($event)"
cdkDropListData="dataSource"
[cdkDropListDisabled]="dragDisabled">
...
<ng-container matColumnDef="order">
<mat-header-cell *matHeaderCellDef>Order</mat-header-cell>
<mat-cell *matCellDef="let element">
<mat-icon class="dragCursor" (mousedown)="dragDisabled = false;">reorder</mat-icon>
</mat-cell>
</ng-container>
...
<mat-row *matRowDef="let row; columns: displayedColumns;" cdkDrag [cdkDragData]="row"></mat-row>
</mat-table>
并且在组件中ts
file:
export class TableBasicExample {
dragDisabled = true;
drop(event: CdkDragDrop<any[]>) {
// Return the drag container to disabled.
this.dragDisabled = true;
// other code on drop event
//
const previousIndex = this.dataSource.findIndex((d) => d === event.item.data);
moveItemInArray(this.dataSource, previousIndex, event.currentIndex);
this.table.renderRows();
}
}
工作示例
https://stackblitz.com/edit/angular-materials-table-with-drag-and-drop-nvyyy4 https://stackblitz.com/edit/angular-materials-table-with-drag-and-drop-nvyyy4
更新2022-05-16
Angular Material v13 中仍然存在问题。
工作示例@angular/cdk
& @angular/material
- v13.3.7
(还包含@Max Leske 建议的改进):
https://stackblitz.com/edit/angular-ivy-gof2zv https://stackblitz.com/edit/angular-ivy-gof2zv