Reputation: 1023
I have an Angular material table with two fields:
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container matColumnDef="Field1">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Field1</th>
<td mat-cell *matCellDef="let element"> {{element.Field1}} </td>
</ng-container>
<ng-container matColumnDef="Field2">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Field2</th>
<td mat-cell *matCellDef="let element"> {{element.Field2}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
I import the following modules:
Material.MatTableModule,
Material.MatSortModule,
Then I declare the sort as follows:
@ViewChild(MatSort) sort: MatSort;
I populate the dataSource from an external API by calling the following method in the constructor:
populateTable() {
this.requestHttpService.getStuff()
.subscribe(data => {
this.results = data;
this.dataSource = this.results;
this.dataSource.sort = this.sort;
},
...
As you noticed I'm trying to attach sort after the dataSource is loaded.
I have also tried to attach sort in ngAfterViewInit() and couple of other place but no mater what I do it doesn't work.
Any idea?
Upvotes: 0
Views: 2157
Reputation: 3421
You need to make few changes, move code to ngAfterViewInit
since MatSort
is not available till ngAfterViewInit
and initialize table datasource as below:
this.dataSource = new MatTableDataSource(this.results);
Upvotes: 1