Angualar Material Table with Drag & Drop Expanding Rows

November 28, 2022 · 6 min readLucian Ciobanu
Tags:AngularAngularMaterial

As I spend more and more time working for this client from the USA, the requirements are also getting more and more interesting. The business team and PO want to change the way we view some data. In the past the team has implemented for them a componenta factory which creates infinite components within one component - more about that implementation can be found here. The new requirement is to have expanding rows if a record has children and for a user to be able to drag and drop children to other parents ore to make other children parents. I'm really set on using Angular Material as much as I can because, although it might be harder to twist and bend it into what you are trying to develop, it comes with a lot of tried and tested code.

In the Angular HTML file, I'm creating the structure for expanding and drag and drop cdk as such:

<mat-table
           [dataSource]="dataSource"
           class="mat-elevation-z8 node-item parent-table"
           cdkDropList
           [cdkDropListData]="dataSource.data"
           (cdkDropListDropped)="drop()"
           [cdkDropListSortingDisabled]="true"
           [attr.data-parent-id]="parentId"
           [attr.data-id]="parentId"
>
  <ng-container matColumnDef="Name">
    <mat-header-cell *matHeaderCellDef>
      <span [style.paddingLeft.px]="40">Name</span>
    </mat-header-cell>
    <mat-cell *matCellDef="let data">
      <button mat-icon-button
              [style.visibility]="!data.expandable ? 'hidden' : ''"
              [style.marginLeft.px]="data.level * 16"
              (click)="expand(data)"
      >
        <mat-icon class="mat-icon-rtl-mirror">
          {{treeControl.isExpanded(data) ? 'expand_more' : 'chevron_right' }}
        </mat-icon>
      </button>
      {{data.Name}}
    </mat-cell>
  </ng-container>
  <ng-container matColumnDef="Order">
    <mat-header-cell *matHeaderCellDef>Order</mat-header-cell>
    <mat-cell *matCellDef="let data">{{data.Order}}</mat-cell>
  </ng-container>
  <ng-container matColumnDef="Type">
    <mat-header-cell *matHeaderCellDef>Type</mat-header-cell>
    <mat-cell *matCellDef="let data">{{data.Type}}</mat-cell>
  </ng-container>
  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row
           *matRowDef="let row; columns: displayedColumns"
           cdkDrag
           [cdkDragData]="{draggedId: row.ID, draggedParentId: row.ParentID}"
           (cdkDragMoved)="dragMoved($event)"
           class="node-item"
           [attr.data-order]="row.Order"
           [attr.data-parent-id]="row.ParentID"
           [attr.data-id]="row.ID"
           [attr.id]="'node-' + row.ID"
 ></mat-row>
</mat-table>
  

In the HTML file, not only am I building the structure but I'm also passing important information for the drag and drop cdk implementation.

Below I'll add the most important properties in the .ts file

transformer = (node: Expand, level: number) => {
  return {
    ParentID: node.ParentID,
    ID: node.ID,
    expandable: !!node.children && node.children.length > 0,
    Name: node.Name,
    Order: node.Order,
    Type: node.Type
  } as Expand
}

treeControl = new FlatTreeControl<Expand> {
  (node) => node.level,
  (node) => node.expandable
);

treeFlattener = new MatTreeFlattener(
  this.transformer,
  (node) => node.level,
  (node) => node.expandable,
  (node) => node.children
)

dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);

dragMoved(event) {
  let elementOverWhichMouse = this.document.elementFromPoint(
    event.pointerPosition.x,
    event.pointerPosition.y
  );
  if (!elementOverWhichMouse) {
    this.clearStylingDragDrop();
    return;
  }
  let container = elementOverWhichMouse.classList.contains('node-item')
    ? elementOverWhichMouse
    : elementOverWhichMouse.closest('.node-item');
  if (!container) {
    this.clearStylingDragDrop(true);
    return;
  }
  this.dropActionTodo = {
    targetId: container.getAttribute('data-id');
  }
  const targetRect = container.getBoundingClientRect();
  const oneThird = targetRect.height / 3;
  if (event.pointerPosition.y - targetRect.top < oneThird) {
    this.dropActionTodo['action'] = 'before';
  } else if (event.pointerPosition.y - targetRect.top > 2 * oneThird) {
    this.dropActionTodo['action'] = 'after';
  } else {
    this.dropActionTodo['action'] = 'inside';
  }
  this.addStylingDragDrop();
}

drop() {
  //validation & api calls would be triggered here
  if(this.validation()) {
    this.clearStylingDragDrop(true);
    return;
  }
}

expand(node: Expand) {
  this.treeControl.toggle(node);
}

addStylingDragDrop(): void {
  this.clearSylingDragDrop();
  this.document.getElementById('node' + this.dropActionTodo.targetId).classList.add('drop-' + this.dropActionTodo.action);
}

clearStylingDragDrop(dropped = false): void {
  if (dropped) {
    this.dropActionTodo = null;
  }
  this.document
    .querySelectorAll('.drop-before')
    .forEach((element) => element.classList.remove('drop-before'));
  this.document
    .querySelectorAll('.drop-after')
    .forEach((element) => element.classList.remove('drop-after'));
  this.document
    .querySelectorAll('.drop-inside')
    .forEach((element) => element.classList.remove('drop-inside));
}

And here it is, one of the most complex implementations I've done so far. I had a lot of challenges in making both expanding and table work together and making sure each element has all the data that I need to perform the drag & drop related operations.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery