Back to Home

Mastering Angular Material Data Tables

angular2 · table · material design

Mastering Angular Material Data Tables


Hello! In general, the documentation of this component covers many issues of use, but in the process of real development there are many pitfalls. I would like to talk about them and how I fought with them.

Code readability


Example from the documentation:


    ...
  
    ...
  
  ...

I will say that this does not correspond to my concept of readability. And it will be absolutely terrible if there are more than 5 columns in the table. And * ngFor comes to the rescue (material data table is an add-on over cdk data table, therefore dynamic columns are possible). Here's how it might look more readable:

{{ column.header }}{{ column.cell(row) }}
  ...

columns = [
  {key: 'position', header: 'Position', cell: (row: Row) => `${row.position}`},
  {key: 'weight', header: 'Weight', cell: (row: Row) => `${row.weight}`},
  ...
];

I also want to note that sorting does not work with a field of type array. Therefore, I had to hardcode with the addition of a number to the names of dynamic fields.

Sticky headers



.mat-header-row {
  position: sticky;
  top: 0;
  background: white;
  z-index: 9999;
}

Such a simple solution, and your header line freezes when scrolling.

You can not be limited to it and make a static sidebar for convenience when scrolling data horizontally (an example in the picture shows how this works). It uses the [ngStyle] attribute for each dynamic cell (the first two for each row with similar styles above).

Horizontal scrolling also breaks line breaks (and for sticky parts, the background breaks). The flex attribute here turned out to be a great helper.


A little bit about the filter


The table page has an important note about default filtering:
For example, the data object {id: 123, name: 'Mr. Smith ', favoriteColor:' blue '} will be reduced to 123mr. smithblue

Personally, I find this approach unacceptable, because often when filtering visually there is confusion (no coincidences are observed). The most suitable option would be to filter separately for each visible field. Plus, it is better not to add additional invisible fields with this approach (they will also bring their own confusion). But the developers proposed a solution:
To override the default filtering behavior, a custom filterPredicate function can be set which takes a data object and filter string and returns true if the data object is considered a match.

filterPredicate: ((data: T, filter: string) => boolean)

Problems resolved. I advise you to override the default filtering.

Thanks to the Angular developers for such a powerful framework and for your attention.

Read Next