D.Zet
D.Zet

Reputation: 779

Sorting function not working with generic Angular Material Table

I created my own generic component with Material Table to use it in my application. So the problem is with sorting - it doesn't work at all. The arrow next to the column header shows but nothing happen. I found that it can be problem with ngIf over <table but.. I don't have it (only inside of the table but these are not the problem). Maybe someone can help me with that?

Component:

@ViewChild(MatSort, {static: true}) sort: MatSort;
@Input() data: any[] = [];
@Input() columns: GridColumn[] = [];
displayedColumns: string[] = [];
dataSource: MatTableDataSource<any>;

ngOnInit() {
for (const column of this.columns) {
  this.displayedColumns.push(column.id);
}

this.dataSource = new MatTableDataSource<any>(this.data);
}

ngAfterViewInit() {
this.dataSource.sort = this.sort;
}

getValue(object: any, path: string) {
return getNestedValue(object, path);
}

And the template:

<table class="w-100" mat-table [dataSource]="data" matSort>
 <ng-container *ngFor="let column of columns">

  <ng-container *ngIf="!column.content" cdkColumnDef="{{column.id}}">
   <th cdk-header-cell *cdkHeaderCellDef mat-sort-header>{{column.label | translate}}</th>
   <td cdk-cell class="position-relative" *cdkCellDef="let row">{{row[column.id]}}</td>
  </ng-container>

  <ng-container *ngIf="column.content" cdkColumnDef="{{column.id}}">
   <th cdk-header-cell *cdkHeaderCellDef>{{column.label | translate}}</th>
   <td cdk-cell class="position-relative" *cdkCellDef="let row">
    <ng-container [ngTemplateOutlet]="column.content"
                  [ngTemplateOutletContext]="{record: row, value: column.field ? getValue(row, column.field) : null}">
    </ng-container>
   </td>
  </ng-container>

 </ng-container>

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

EDIT: Stackblitz: https://stackblitz.com/edit/angular-b9cdqt

Upvotes: 1

Views: 925

Answers (1)

yurzui
yurzui

Reputation: 214305

The reason for this is that there is no reactive flow in your example.

You have no connection to MatTableDataSource since you passed plain array to dataSource input property instead.

A quick fix should be:

[dataSource]="dataSource" 

Forked Stackblitz

Upvotes: 1

Related Questions