how to sort mat table when the select value from the dropdown list: I have a table that contains "status, date" column, and drop-down list that contains all the column names I want to sort the table by values that contain column names
1 Answer
You can use the MatSort Header from Angulars Material Table and emit a sortChange event.
These headers should be contained within a parent element with the matSort directive, which will emit an matSortChange event when the user triggers sorting on the header.
E.g.:
export class TableSortingExample implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource(ELEMENT_DATA);
@ViewChild(MatSort) sort: MatSort;
selectedColumn = 'name';
ngOnInit() {
this.dataSource.sort = this.sort;
this.changeSortedColumn();
}
changeSortedColumn() {
const sortState: Sort = {active: this.selectedColumn, direction: 'asc'};
this.sort.active = sortState.active;
this.sort.direction = sortState.direction;
this.sort.sortChange.emit(sortState);
}
Together with your Material Table and a selectionBox:
<mat-select [(value)]="selectedColumn" (selectionChange)="changeSortedColumn()">
Here is the depending working Stackblitz.
4 Comments
Mona
the sort is not working (either from table column or from the list :( )
zerocewl
Where it is not working? The Stackblitz works fine. You have to share at least some parts of your code or a minimal reproduciable example if anyone should help you ;-)
zerocewl
Please have a look at stackoverflow.com/help/someone-answers too
Simon
@Mona, possibly you forgot to import the MatSortModule in your NgModule. Having the MatSort in the component is not enough.