Smart Mat-Table Part 1 : Reusable & Customizable

Benjamin Maisonneuve
3 min readDec 8, 2020

--

This is the first article of a small series in order to created highly reusable and customizable mat-table components while reducing boilerplate.

In this article we will see a simple way to define a mat-table component for an entity and make it reusable and simply customizable.

Introduction

Let’s say we want to display a table of users (with firstname, lastname, mail and job). We want to make a UsersTableComponent that is reusable because we may use this table multiple times in our app. It also needs to be customizable because in some page we may have to display the table without some columns (exclude the job column for example). Thankfully the mat-table component from Angular Component make it easy.

Mat-table needs 3 things to show a table :

  • a DataSource too handle data
  • a templates for each column’s header and cell
  • the list of columns to display

To make our UsersTablesComponent DUMB and resuable we will set the DataSource and list of columns to display as inputs. So our UsersTableComponent will only define the template for the columns. And this is the parent’s responsability to define the data (or retrieve it from an API) and which columns to display.

Implementation

Let’s define our User interface like so

export interface User {
firstname: string;
lastname: string;
mail: string;
job: string;
}

We will define a simple UserDataSource with a static list of users using the User interface.

We can now create our UsersTableComponent that will take a UserDatasource as an input and the list of columns to display.

Basically the UsersTableComponent define how to display the columns. For example the Firstname and Lastname are simply displayed in a span. The Mail are shown in a <a> tag to open new mail on click. And we just set a class for the job to underline it. The UsersTableComponent does noting more.

Et voila 🍾 We can now simply use the UsersTableComponent and define which columns to show and in which order to show them.

The second table does not show the Firstname column and the make the job column first.

You can find a working example in the following stackblitz.

Conclusion

Here is how we can use the power of mat-table with the datasource and the columns to create a simple yet reusable and customizable table component for an entity.

In the part 2 of this series, we will see how to remove the HTML boilerplate for common columns (like firstname and lastname).

In part 3 we will see how to improve customization by being able to inject custom columns in table from parent.

Here is the full github repository of the series. This part is the SimpleUsersTableComponent → https://github.com/BobBDE/smart-mat-table

Thank you for reading :) !

--

--

Benjamin Maisonneuve

Freelance web developer using angular and angular material since v2