I've been doing some prototype work with the ngMaterial grid and had a problem where the grid would not sort. Here are a few things to check if this happens to you.
- Import the MatSortModule Module: Be sure that your @NgModule definition includes the MatSortModule:1@NgModule({
2 declarations: [
3 AppComponent,
4 ],
5 imports: [
6 BrowserModule,
7 BrowserAnimationsModule,
8 MatTableModule,
9 MatSortModule,
10 ],
11 bootstrap: [AppComponent]
12})Without this, the sorting will not work.
- Specify the matSort header: Be sure to specify the matSort header on your table grid: 1<table mat-table [dataSource]="rowData" matSort class="mat-elevation-z8"
2>
3// rest of the table definition here
4</table>Without that you won't be able to click on the headers.
- Wrap Your Data Source in a MatTableDataSource: If you do not wrap your own datasource--probably an array--in the MatTableDataSource class you'll have to write your own sorting algorithm to affect your data because it won't work out of the box. 1this.rowData = new MatTableDataSource(myRowDataArray);
Do this because it makes your life easier.
- Tell the data source about your sort: Your MatTableDataSource does not know about the sort by default. Get a ViewChild instance to the sort in your code: 1@ViewChild(MatSort) sort: MatSort;
And apply that:
1ngOnInit() {
2 this.rowData.sort = this.sort;
3 }Hopefully you got this far and your table is sorting now.
- Write Your Own Sort: If you're avoiding using the MatTableDataSource for some reason, you'll have to write your own sort algorithm. In the HTML, listen for the matSortChange event:1<table mat-table [dataSource]="rowData" matSort class="mat-elevation-z8" (matSortChange)="onMatSortChange()">
2// rest of the table definition here
3</table>And in your code:
1onMatSortChange(){
2 // do something to modify your data source here.
3 }
I've found the documentation lacking for ngMaterial, but so far we plan on plunging ahead with it. Hopefully this helped someone out.