Angular Material table — complete example

Sri M
3 min readMar 8, 2020

--

In this article, let’s explore the features of angular mat-table. I will start with basic table and start adding the following features to it.

Pagination

Sorting

Filtering

Sticky Rows/Columns

Column Re-ordering

Angular mat table example

I started off with new angular project created using CLI and added Material to the project. I added a simple data json and displaycolumns in the ts file.

And the HTML looks as below. This will render a table. Nothing fancy here, I just defined the row and column templates and iterated over the displayColumns and pulled that data from the datasource.

Add Pagination:To add a paginator, create an instance of MatPaginator and set it to the datasource. Following are the changes in ts file.

And in the HTML just a <mat-paginator> tag. You will have to specify the following:

pageSize — The #rows to be shown on each page
pageSizeOptions — The selectable page sizes in the dropdown
showFirstLastButtons — optional directive when provided shows the first/last buttons on the paginator

Add Sorting: To enable sorting, add the matSort directive on the table and mat-sort-header to each header you want to sort on. matSortChange event will be triggered on every click on the sortable header. You just have to capture this event and implement your sorting logic. My HTML and ts changes are shown below.

Add Filtering: Firstly I added a filter icon to all the headers and an input field where the user can enter a filter text. It is hidden by default. When the user clicks on filter icon the input field is rendered and the filtering happens on blur of the input field.

Note: Filter icon is added to header and this table has sorting enabled. So the clicks on filter icon will also trigger sort change event. To prevent it I used stopPropagation() call.

The implementation of filter is shown below:

Sticky Rows & Columns: To implement this, I first added a div container around the table and reduced the width and height to produce the scroll bars.

To make the header row sticky just add sticky:true to the mat-header-row
To make the first column sticky, add [sticky]=”true” for first column

Column Re-ordering: Mat-table does not provide this out of box, but can be achieved using cdk library. Please visit my other article to see how it is done — https://medium.com/@srik913/angular-mat-table-and-column-reordering-61dc130b7e69

This entire example can be found on my github.

Happy Learning!

--

--

Sri M

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