Search code examples
angularangular-materialdrag-and-drop

Angular material table drag/drop do not allow drop in the first column


I have a dynamic material table with the first column with options to view details, edit etc. So I only want the drop to be allowed after the first column. How I can attain this or use the cdkDragBoundary with in mat table th

  <table mat-table [dataSource]="dataSource" 
         cdkDropList
         cdkDropListOrientation="horizontal"
         (cdkDropListDropped)="drop($event)">
    <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns; let i=index" [sticky]="isFirstColumn(column)">
      <th mat-header-cell *matHeaderCellDef cdkDrag>
        <ng-container *ngIf="!isFirstColumn(column)">
          <div style="float: right">
            <button type="button"
                    class="drag-handle sm-icon-button"
                    [disabled]="isEditDisabled"
                    mat-icon-button cdkDragHandle>
              <mat-icon>drag_handle</mat-icon>
            </button>
          </div>
          {{ column}}
        </ng-container>
      </th>
      <td mat-cell *matCellDef="let element" class="w-100 col-left">
        <ng-container *ngIf="isFirstColumn(column)">
          <button mat-icon-button>
            <mat-icon>
              list
            </mat-icon>

          </button>
            <button mat-icon-button
                    [disabled]="isEditDisabled"
                    (click)="onEdit(element)">
              <mat-icon>
                edit
              </mat-icon>

            </button>
          </ng-container>
          <span>{{element[column]}}</span>
        </ng-container>
        <ng-container *ngIf="!isFirstColumn(column)">
          <ng-container *ngIf="editing.Id && element.Id === editing.Id">
            <input id="{{column}}{{i}}" [(ngModel)]="element[column]" size="10" />
          </ng-container>
          <ng-container *ngIf="!editing.Id || element.Id !== editing.Id">
            {{element[column]}}
          </ng-container>
        </ng-container>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
 


Solution

  • I had the same problem but managed to solve it by the following code. Users still can drag and drop but after drop, we are preventing the original array from changing.

    drop(event: CdkDragDrop<any>) {
     if(event.currentIndex == 0) {
       return;
     }
     moveItemInArray(this.dataSource, event.previousIndex, event.currentIndex);
    }