Reputation: 143
I use a lot of tables in this project, and MatSort is working fine in all the other components. However, I created this new component and, though I can get the arrows to show when I click on the table headers, the data itself doesn't get sorted.
I've compared every line of my project to the Sort Header Angular demo as well as my components that are already working fine, and I cannot find where I'm going wrong. The data in question shown below is an array of objects. I've simplified it here showing only the sequence
value of each object.
<table mat-table [dataSource]="dataSource" matSort *ngIf="dataSource">
<ng-container matColumnDef="sequence">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Sequence</th>
<td mat-cell *matCellDef="let item">{{ item.sequence }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay"></tr>
</table>
columnsToDisplay = [
'sequence'
];
dataSource: MatTableDataSource<SuiteItem>;
@ViewChild(MatSort) sort: MatSort;
constructor(
private keyCodeService: KeyCodeService
) {
}
ngOnInit(): void {
this.keyCodeService.getSequences().subscribe(
data => {
this.dataSource = new MatTableDataSource(data);
this.dataSource.sort = this.sort;
}
);
}
I have the matSort
directive in place as well as the the mat-sort-header
s, the module is imported (and works fine on other components), and a function runs the this.dataSource.sort = this.sort
method, so when I click the headers, they should toggle between sorting ascending and descending. Instead, though the arrow appears, nothing happens to the data.
Upvotes: 3
Views: 1227
Reputation: 133
<table mat-table [dataSource]="dataSource" matSort [hidden]="dataSource.data.length != 0">
<ng-container matColumnDef="sequence">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Sequence</th>
<td mat-cell *matCellDef="let item">{{ item.sequence }}</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay"></tr>
</table>
You can't use *ngIf with sorting. It will not work. Try using this code with [hidden] instead.
Upvotes: 1