-1

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
  • Can you show what you have tried for it? :) Commented Mar 5, 2020 at 16:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

the sort is not working (either from table column or from the list :( )
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 ;-)
Please have a look at stackoverflow.com/help/someone-answers too
@Mona, possibly you forgot to import the MatSortModule in your NgModule. Having the MatSort in the component is not enough.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.