angularangular-materialangular-cdkangular-cdk-drag-drop

Disable drag and drop for table rows based on condition


Code below can drag and drop table rows and re-order table rows by dragging and dropping. However I want to disable drag and drop certain rows when item.disable is true and not sure how to do it. How can I do it?

<table
  [dataSource]="items"
  class="mat-elevation-z1"
  mat-table
  cdkDropList
  [cdkDropListData]="items">
  <ng-container matColumnDef="dragHandle">
    <th mat-header-cell *matHeaderCellDef></th>
    <td mat-cell *matCellDef="let element" class="grab-test">
      <svg
        xmlns="http://www.w3.org/2000/svg"
        height="41"
        viewBox="0 0 23 26"
        width="45"
        style="margin-top: 10px">
        <path d="M0 0h24v24H0V0z" fill="none" />
        <path
          d="M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2zm-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"
        />
      </svg>
    </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th *matHeaderCellDef mat-header-cell>Name</th>
    <td *matCellDef="let element" mat-cell class="drag-row">
      <input matInput type="text" [(ngModel)]="element.name" />
    </td>
  </ng-container>

  <tr *matHeaderRowDef="displayedColumns" mat-header-row></tr>
  <tr *matRowDef="let row; columns: displayedColumns" 
      mat-row 
      cdkDrag 
      [cdkDragData]="row">
  </tr>
  <div *cdkDragPlaceholder></div>
</table>

Solution

  • There is a disabled property for CdkDrag.
    See for more information the official documentation here.

    So for your case you can simply do:

    <tr *matRowDef="let row; columns: displayedColumns" 
      mat-row 
      cdkDrag 
      [cdkDragData]="row"
      [cdkDragDisabled]="row.disable">
    </tr>