【问题标题】:When using mat-table (not classic html table), how to apply cdkDropList to tbody?使用 mat-table(不是经典的 html 表)时,如何将 cdkDropList 应用于 tbody?
【发布时间】:2021-08-01 22:32:51
【问题描述】:

我目前正在使用 mat-table 作为文档中的这个简单示例:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  ...

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

为了能够更改行的顺序,然后我使用 cdk 拖放,使用 mat-row 右侧的 cdkDrag 指令和 mat-table 右侧的 cdkDropList 指令。我还需要使用其他属性,如 cdkDropListSortPredicate,但我会尽量简单地解释我的问题: 我观察到事件和谓词的几个问题。在进行操作时检查 html 代码时,我看到占位符有时被放置在 tbody 之外,因为附加到 CdkDropList 的元素是表,而不是要重新排序的行所在的 tbody。

那么,正如主题中所提到的,您是否曾经成功地将 cdkDropList 指令应用于由角表(mat-table)生成的 tbody?或者你能想出一个解决办法吗? (我尝试创建自己的指令来修改附加到 CdkDropList 的元素但没有成功)

更新 1:我观察到这些问题,尤其是在拖动元素来自另一个列表的情况下。它是在 tbody 外部生成的占位符。所以,这个问题不能用 CdkDropListDropped 解决。

更新 2:这里是 the stackblitz link 以了解我的问题。在该示例中,其中一个问题是,如果您越过标题,我不希望占位符出现在列表的第一个位置。因为从视觉上看,您可能看起来可以将元素放在这里。 PS:一旦我解决了这个问题,对我来说另一个困难将是根据条件隐藏占位符。如果在将元素拖动到正确位置之前将其拖动到错误位置,则占位符将出现在最后一个位置。我不想那样。

【问题讨论】:

    标签: html angular typescript mat-table angular-cdk-drag-drop


    【解决方案1】:

    以下解决方案将为您提供帮助。您可以使用 cdkDropList 呈现正文中的表格行

    stackblits solution

     dropTable(event: CdkDragDrop<PeriodicElement[]>) {
        const prevIndex = this.dataSource.findIndex(d => d === event.item.data);
        moveItemInArray(this.dataSource, prevIndex, event.currentIndex);
        this.table.renderRows();
    }
    

    【讨论】:

    • 这并不能解决我的问题。我的问题是在项目发布之前,它是针对生成的占位符的。我正在更新帖子以澄清它与拖动元素来自另一个列表时生成的占位符有关。
    • @RobinE 请在stackblitz分享代码
    • 我已经更新了我的 stackblitz 帖子(更新 2)
    猜你喜欢
    • 2017-11-18
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2011-10-03
    • 2010-11-28
    • 1970-01-01
    相关资源
    最近更新 更多