0
votes

Using Angular Material, I have a Material table with MatSort to allow sorting of some (but not all) columns and drag and drop on the column headers to allow changing column order.

The problem is: columns for which sorting is disabled, cannot be dragged

The problem can be reproduced in https://stackblitz.com/edit/angular-mat-table-columns-draggable?file=src%2Fapp%2Fapp.component.html by adding the following line to

[disabled]="i%2==0"

Now only the second and the fourth column can be dragged.

1

1 Answers

0
votes

This is because the whole component (mat-header-cell) gets disabled, which disables the click event, which in turn makes the cdkDrag events not fire at all. While it's a bit ugly solution, you can conditionally switch the template of the mat-header-cell to either have or not have the mat-sort-header directive. Then you don't have to fall back to the [disabled] input:

<ng-container *ngIf="column.canSort">
  <mat-header-cell *matHeaderCellDef
    cdkDropList
    cdkDropListLockAxis="x"
    cdkDropListOrientation="horizontal"
    (cdkDropListDropped)="dropListDropped($event, i)"
    cdkDrag
    (cdkDragStarted)="dragStarted($event, i)"
    [cdkDragData]="{name: column.field, columIndex: i}" mat-sort-header>
    {{ column.field }}
  </mat-header-cell>
</ng-container>
<ng-container *ngIf="!column.canSort">
  <mat-header-cell *matHeaderCellDef
    cdkDropList
    cdkDropListLockAxis="x"
    cdkDropListOrientation="horizontal"
    (cdkDropListDropped)="dropListDropped($event, i)"
    cdkDrag
    (cdkDragStarted)="dragStarted($event, i)"
    [cdkDragData]="{name: column.field, columIndex: i}">
    {{ column.field }}
  </mat-header-cell>
</ng-container>

In the above example I've added the canSort property on the column, but of course you can use the above predicate of yours ("i%2==0").

Hope this helps.