Search code examples
angularangular-materialmat-table

Angular material - mat-table dynamic footer/header rowDef


I'm trying to conditionally display the footer-row of my mat-table.

Based on this discussion, I know that somehow, I have to use removeFooterRowDef to remove it and I guess addFooterRowDef or setFooterRowDef to bring another.

But I can't find a proper explanation on how to use one of these.

Note that I have tryed to wrap the footer-row in an ng-container.

<ng-container *ngIf="hasFooter">
    <tr mat-footer-row *matFooterRowDef="footerRowDef"></tr>
<ng-container>

but even if hasFooter is false, the row is still there.


Solution

  • Based on the answer on this question, I found out that it is used in combination with viewChild like in the template, there is

    <ng-container>
        <tr *matFooterRowDef="columns" mat-footer-row></tr>
    </ng-container>
    

    and in the component class

    @ViewChild(MatFooterRowDef, {static: true}) footerDef: MatFooterRowDef;
    @ViewChild(MatTable, {static: true}) table: MatTable;
    
    removeFooter() {
        this.table.removeFooterRowDef(this.footerDef);
    }
    
    addFooter() {
        this.table.setFooterRowDef(this.footerDef);
    }
    

    To add a new footer, we would call addFooterRowDef but I call setFooterRowDef to override any existing footer.

    All other methods for rowDef and headerRowDef work the same way. And columnDef also, I guess.

    I leave it here if ever anyone needs it.