Angular 8|9 Material Table Column Width, Text Alignment Customization

Angular Material provides an awesome fully-featured data-table component that can be easily implemented in an Angular application. The datatable UI component provided by Material is based on the material design provides many features like Pagination, Sortable columns, Filter data, Frozen Columns, and Rows, etc.

Although Material data-tables provides high-end functionalities, small things can eat-up most of our time.

One such case is sometimes developers find it difficult to fix the width of columns according to needs. In Angular Material data-table each column is equally divided according to the width of the container where it is kept.

But there are some cases where we may want some columns to have fix width having only icons or some ID.

Before:

After:

 

Let’s create a Material table to implement these tricks:

Version Check:

Angular CLI: 9.0.6
Node: 12.15.0

Create an Angular project

Using NG CLI create new Angular project by running the following command:

 

Move to project root:

 

Install Angular Material

After creating the project, install the Material package in the project to use data-table component UI.

Run the following command to install the Material package by answering a few questions:

Add Material Data Table

To use data-table add the MatTableModule in app.module.ts file:

We also need HttpClientModule to fetch remote data to build data-table.

Update app.component.ts file to define data-table columns and fetch data by calling the getRemoteData() as shown below:

In the app.component.html file replace below HTML code:

Now we have a data-table to apply our tricks:

Custom Width on Material Data Table Columns

To apply custom width to columns we can create helper classes with width provided in pixes as shown below:

You can create any number of these custom width classes according to your requirements.

After that just add them to the <th> element in the table above.

How to Align Text in columns of data-table?

In a similar way just create classes as shown below:

Which can be added to <th> elements:

For Data-Tables using Component Elements as shown below:

We can use [ngClass] directive to add classes to Column and Cells but instead of width, we need to use max-width to columns as well as to cells because components use FLEX layout to define widths.

Update CSS classes:

 

Leave a Reply

avatar
  Subscribe  
Notify of