mat table sticky footer row with sum

June 10, 2021 · 2 min readLucian Ciobanu
Tags:AngularAngularMaterial

Here's a cool way to add a sticky footer row with the sum on columns in Angular Material:

  1. Define the footer cell as such:
<ng-container matColunDef="name">
  <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
  <mat-cell *matCellDef>{{ rowDataSource.name }}</mat-cell>
  <mat-footer-cell *matFooterCellDef>Total</mat-footer-cell>
 </ng-container>
<!-- another column for the actual numbers -->
<ng-container matColunDef="salary">
  <mat-header-cell *matHeaderCellDef>Salary</mat-header-cell>
  <mat-cell *matCellDef>{{ rowDataSource.salary | number }}</mat-cell>
  <mat-footer-cell *matFooterCellDef>{{ sum("salary") | number: '.2' }}</mat-footer-cell>
 </ng-container>
<!-- define the rows -->
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
<mat-footer-row *matFooterRowDef="displayedColumns; sticky: true"></mat-footer-row>

If you're familiar with material table this is straight forward except maybe the fact that I've added the number pipe which displays the value in US locale meaning it uses "," as a thousands separator. If you use number: '.2', this tells the pipe to dispaly a number as 1,234.01 (, as thousands separator and two digits after the decimal separator).

Also, in the third part of the above code, we define each of the rows, including the footer which has "sticky: true" which will make it stick even when we browse through the pages.

That's pretty much it, I'll add the sum property form the class because I'm still wrapping my head around reducers and this was a special implemetation for me as I'm just passing the object's key and the property I created does all the work.

public sum(key: keyof DataSource) {
  return this.dataSource.data.reduce((a, b) => a + (Number(b[key]) || 0), 0);
}

What I've done here is that sum can take any string which is one of the keys of DataSource interface and then we go through reducing the data array to a single number as:

a is the accumulator and it starts with 0 (notice the last parameter "0" of the reduce metho);
b is the current value of the data array which we are reducing and we get the Number of that value from property key.

Hope this helped!

Cheers,
Lucian!

Picture of author

Web Development & Software Delivery