0

I succesfully applied the sort mechanism for my angular material design table but what I'm missing is that the table sorts itself when I load the page. It works when I click on the column header of the column I want to sort but not at startup. The only solution I can find is the (matSortChange) but I don't want to define a sort function because obviously angular knows the sort function but just does not apply it when the table is created. One problem I may be facing is that I create the dataSource empty because I add the data in the ngOnInit() function.

I also tried matSortActive="name" matSortDirection="desc" and the arrow is there but it is not sorted, maybe because I have only 0's at the beginning before changing the numbers. But I don't know how I could delay this.

Greetings

angpro147
  • 1
  • 1
  • Welcome to StackOverflow! Please take the [tour] (and earn a badge while you are at it) / Also read our [ask] page and [edit] your question to improve it. Good questions tend to receive quicker, better answers from the community. For starters, please include a [mcve] to your question. Otherwise, it might take a lot more time and a heap of guessing to figure *exactly* where the issue lies. – blurfus Apr 07 '21 at 23:47
  • Does this answer your question? [Default sorting in Angular Material - Sort header](https://stackoverflow.com/questions/46743115/default-sorting-in-angular-material-sort-header) – user733421 Apr 08 '21 at 09:07

1 Answers1

0

just before asing the sort to the data source:

ngAfterViewInit() {
    this.sort.active="name";
    this.sort.direction="asc"
    this.dataSource.sort = this.sort;
}

See stackblitz

Eliseo
  • 50,109
  • 4
  • 29
  • 67