1

这就是我遇到的情况,我需要使用 Angular 的 mat-table 和 cdkDragDrop(使用 Angular 8)制作一个列拖放功能。

这是我到目前为止所拥有的。

在 component.html 里面我有:

<mat-table cdkDropList cdkDropListOrientation="horizontal" (cdkDropListDropped)="drop($event)" [dataSource]="dataSource">

  <ng-container *ngFor="let column of columns; let i = index" [matColumnDef]="column.name">

    <mat-header-cell *matHeaderCellDef cdkDrag cdkDragLockAxis="x">
      {{column.title}}
    </mat-header-cell>

    <mat-cell *matCellDef="let element">{{ element[column.name] }}</mat-cell>

  </ng-container>

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

在 component.ts 里面我有:

export class TestClass implements OnInit {
  displayedColumns = ['id', 'firstName', 'lastName', 'email', 'phoneNumber', 'address', 'points', 'Details'];
  .
  .
  .
  columns: any[] = [{
        name: 'id',
        title: 'Id'
      },
      {
        name: 'firstName',
        title: 'FirstName'
      },
      {
        name: 'lastName',
        title: 'LastName'
      },
      {
        name: 'email',
        title: 'Email'
      },
      {
        name: 'phoneNumber',
        title: 'PhoneNumber'
      },
      {
        name: 'address',
        title: 'Address'
      },
      {
        name: 'points',
        title: 'Points'
      },
      {
        name: 'Details',
        title: 'Details'
      },
    ]
    .
    .
    .
  drop(event: CdkDragDrop < any[] > ) {
    moveItemInArray(this.displayedColumns, event.previousIndex, event.currentIndex);
  }

}

这只是我设法在互联网上找到的一个简单的测试代码我发现的 stackblitz 示例 问题是,我无法设法让线路(cdkDropListDropped)="drop($event)"在 ts 中的“drop”函数中触发事件。我尝试了没有表格的功能并且它正在工作,它正在触发事件(和“drop”功能),但是在表格内部,它不起作用。

我想知道你们中是否有人遇到过类似的问题,以及您是否设法解决了这个问题。

4

1 回答 1

4

我在使用 Angular 9.1.12 时遇到了同样的问题。

我在以前版本的 Angular 中找到了这个示例,但是使用相同的代码它对我不起作用(stackblitz)。

所以我使用了这个解决方法(使整个表都可以删除)并且它有效:

<table mat-table [dataSource]="tableDataSource" cdkDropList cdkDropListLockAxis="x"
    cdkDropListOrientation="horizontal" matSort
    (cdkDropListDropped)="dropListDropped($event)">
    <ng-container *ngFor="let disCol of headers; let colIndex = index" matColumnDef="{{disCol.field}}">
        <th mat-header-cell *matHeaderCellDef cdkDrag [cdkDragData]="{name: disCol.field, columIndex: colIndex}"
            mat-sort-header>
            {{disCol.field}}
        </th>
        <td mat-cell *matCellDef="let row "> {{row[disCol.field]}}
        </td>
    </ng-container>
   [...]
</table>
于 2020-10-19T10:31:16.610 回答