角材质 mat-table 中的 cdkDragHandle 没有效果

2024-04-05

我想知道是否可以有一个包含 mat-icon 的单元格定义为

cdkDragHandle。目前它在整行上处于活动状态,但我只想将单个图标用作拖动手柄

这是我正在使用的代码的一部分:

<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8" 
cdkDropList [cdkDropListData]="dataSource"
(cdkDropListDropped)="dropTable($event)">

<ng-container matColumnDef="Order">
  <mat-header-cell *matHeaderCellDef>
    Actions
  </mat-header-cell>
  <mat-cell mat-cell *matCellDef="let element">
    <mat-icon class="dragCursor" cdkDragHandle>reorder</mat-icon>
    {{element.order}}
    <button mat-icon-button (click)="onDeleteClick(element)">
      <mat-icon>delete</mat-icon>
    </button>
  </mat-cell>
</ng-container>

... more column definitions

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" cdkDrag    [cdkDragData]="row" cdkDragLockAxis="y"></mat-row>

我还尝试在 mat-cell 上定义拖动手柄,但无济于事。 有谁知道如何解决这个问题?

提前致谢!


看起来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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

角材质 mat-table 中的 cdkDragHandle 没有效果 的相关文章

随机推荐