ineedtoknow
ineedtoknow

Reputation: 1654

Set Material Sort on Condition - Angular Project

I'm working in an Angular 9 project, using Material.

I have a Material table that supports sorting (Mat-sort). The sort is functioning fine. I now want to only allow certain columns to be sortable on conditions. Is there a way to set the mat-sort-header property to a condition?

Here's my table and columns:

<table mat-table [dataSource]="dataSource" matSort (matSortChange)="setSortInRoute()">
    <ng-container *ngFor="let column of tableConfig.columns">
      <ng-container matColumnDef="{{ column.columnDef }}">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>{{ column.title }}</th>
        <td mat-cell *matCellDef="let row">
          {{ row[column.dataProperty[0]] }}
        </td>
      </ng-container>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr
      mat-row
      *matRowDef="let row; columns: displayedColumns"
      (click)="goToDetails(row)"
    ></tr>
  </table>

I have tried setting the mat-sort-header property to a condition, like this: [mat-sort-header]="sortColumn" where sortColumn is a boolean var. However, even with the var as false, the columns still have the sorting functionality.

I plan on having the condition be a boolean var that comes from the tableConfig.columns, it will probably be tableConfig.columns.allowSort.

Is there a way to set this property to a condition? If not, any suggestions on how to achieve this?

Thanks

Upvotes: 7

Views: 4826

Answers (1)

JEWEL JACOB
JEWEL JACOB

Reputation: 594

By default the mat-table will change the reference column for sorting when clicking on column header. If your intention is to avoid that, you can add a disabled attribute to th with mat-header-cell directive.

... ... <th mat-header-cell *matHeaderCellDef mat-sort-header [disabled]="column.sortingDisabled">{{ column.title }}</th> ... ...

Upvotes: 11

Related Questions