I receive data through http request, the paginator and filter work, but the sorting directive does not work without any error. Therefore, I don't know where I was wrong, please help me out of this.
Here is my code:
component.ts:
displayedColumns = ['token name', 'industry'];
dataSource = new MatTableDataSource();
id: any;
resultsLength = 0;
pageSize = 5;
tokens: Tokens[];
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(private apiService: ApiService) { }
ngOnInit() {
this.loadTokens();
}
loadTokens() {
this.apiService.getTokens()
.subscribe((data: any) => {
this.tokens = data;
this.dataSource.data = this.tokens;
console.log(this.dataSource);
this.resultsLength = this.tokens.length;
}, error => {
console.log(error);
});
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(filterValue: string) {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filter = filterValue;
}
component.html:
<mat-table [dataSource]="dataSource" matSort>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;">
</mat-row>
<ng-container matColumnDef="token name">
<mat-header-cell *matHeaderCellDef mat-sort-header> TOKEN NAME </mat-header-cell>
<mat-cell *matCellDef="let row"> {{row.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="industry">
<mat-header-cell *matHeaderCellDef mat-sort-header> INDUSTRY </mat-header-cell>
<mat-cell *matCellDef="let row" [style.color]=""> {{row.description}} </mat-cell>
</ng-container>
</mat-table>
<mat-paginator #paginator [pageSize]="pageSize" [length]="resultsLength"></mat-paginator>