Angular Mat-table and column reordering

Sri M
2 min readMar 8, 2020

--

In this article I will show you how to add column reordering to an angular mat-table. If you would like to explore other features of mat-table, please see my other article.

Mat-table does not provide this functionality out of the box. But we can achieve it using angular cdk. This library provides several drag-and-drop features. Please visit the official link — https://material.angular.io/cdk/drag-drop/overview

Add the library project using ‘npm install @angular/cdk/drag-drop’

Below are the main Interfaces/directives you should be aware of to implement column re-ordering.

CdkDropList — this is the container that holds the draggable items

CdkDrag: This is the draggable item that can moved inside the CdkDropList

cdkDropListDropped: This event is fired when an item is dropped onto a container

cdkDropListGroup: This is used to hold several CdkDropList containers. All the lists inside a group are connected auotmatically.

cdkDropListLockAxis & cdkDropListOrientation: They are used to control the drag axis and orientation.

The idea is to mark each <th> item as a CdkDropList and CdkDrag. That makes each header a draggable item and drag/drop container. Next we mark the <table> item as cdkDropListGroup that will hold all the header containers and the containers can be moved within the group. We capture the cdkDropListDropped event and rearrange the column within the displayColumns. And I added ‘cdkDropListLockAxis=”x” cdkDropListOrientation=”horizontal” ’ to restrict the drag to horizontal direction.

Below is the code snippet and highlighted are the changes:

And below is the reorder handler code. The id of each container item is the same as the elements in the displayColumns. All I did is found the indices in the array and moved the items in the array.

The whole example can be found on my github.

--

--

Sri M

A seasoned IT professional with emphasis on designing highly available and easily maintainable applications. Freelancer. Husband and a father!