Search code examples
angularangular-materialangular10angular-cdk

cdkDropListDropped never fired in angular 10 and material table


I was using cdkDropList to reorder columns in the material table.

Until the version 8 everything was going fine, but after updating to version 10 the cdkDropListDropped is never fired.

<table mat-table #table [dataSource]="dataSource" 
  cdkDropListGroup>
      <ng-container *ngFor="let disCol of headers; let colIndex = index" matColumnDef="{{disCol.field}}">
          <th mat-header-cell layout-align="start center" class="centered" *matHeaderCellDef
              cdkDropList
              cdkDropListLockAxis="x"
              cdkDropListOrientation="horizontal"
              (cdkDropListDropped)="dropListDropped($event, colIndex)"
              cdkDrag
              (cdkDragStarted)="dragStarted($event, colIndex)"
              [cdkDragData]="{name: disCol.field, columIndex: colIndex}">
            {{disCol.field}}
          </th>
          <td mat-cell layout-align="start center" class="centered" *matCellDef="let row " > {{row[disCol.field]}}
          </td>
      </ng-container>

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

It seems like the cdkDropList and cdkDrag couldn't be included in the same tag.

Does anyone have an idea about what's going on?

Stackblitz with angular 8

Stackblitz with angular 10


Solution

  • Try this

    <table mat-table #table [dataSource]="dataSource" cdkDropListOrientation="horizontal"
           cdkDropList  (cdkDropListDropped)="drop($event)">
      <ng-container *ngFor="let disCol of headers; let colIndex = index" matColumnDef="{{disCol.field}}">
        <th mat-header-cell layout-align="start center" class="centered" *matHeaderCellDef
            cdkDropList
            cdkDropListLockAxis="x"
            cdkDropListOrientation="horizontal"
            (cdkDropListDropped)="dropListDropped($event, colIndex)"
            cdkDrag
            (cdkDragStarted)="dragStarted($event, colIndex)"
            [cdkDragData]="{name: disCol.field, columIndex: colIndex}">
          {{disCol.field}}
        </th>
        <td mat-cell layout-align="start center" class="centered" *matCellDef="let row " > {{row[disCol.field]}}
        </td>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"
          style="pointer-events: none;"
      >
      </tr>
    </table>
    

    and in .ts

    drop(event: CdkDragDrop<string[]>) {
        moveItemInArray(this.displayedColumns, event.previousIndex, event.currentIndex);
      }
    

    and in You .ts add this

    import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';