Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using conditional attribute binding with mat-header-cell

I'm using mat-table with Angular and attempting to make my table a reusable component. I have some options that get passed to the template like:

const columns: TableColumn[] = [
            {
                title: 'Person',
                colKey: 'person',
                sort: {
                    sortable: false
                }
            },
            {
                title: 'Date',
                colKey: 'date',
                sort: {
                    sortable: true,
                    selected: true,
                    sortAsc: false
                }
            }
        ];

I'm trying to add the mat-sort-header based on those options.

<ng-container *ngFor="let head of options.columns" matColumnDef="{{head.colKey}}">
    <mat-header-cell *matHeaderCellDef [attr.mat-sort-header]="head.sort.sortable">{{head.title}}</mat-header-cell>
    <mat-cell *matCellDef="let item">{{item[head.colKey]}}</mat-cell>
</ng-container>

So since the date column is sortable, I'd expect that to add the mat-sort-header attribute, but this doesn't seem to be working.

like image 649
Gregg Avatar asked Jul 30 '26 10:07

Gregg


1 Answers

Angular won't apply mat-sort-header directive in this case.

Your issue can be easily solved by adding [disabled] binding like:

 <mat-header-cell *matHeaderCellDef  mat-sort-header [disabled]="!head.sort.sortable"

disabled is an @Input binding from MatSortHeader directive that component to disable sort functionality for this column.

like image 119
yurzui Avatar answered Aug 01 '26 03:08

yurzui