0

I'm using Mart Sort Header component from Angular Material.

This is my async function to get data.


 //DataSource variable
 dataSource: MatTableDataSource<any[]> = new MatTableDataSource([] as any[])
 
 getUsers() {
    this.loading = true
    this.authService
      .getAllUsersData()
      .then((users: any[]) => {
        this.dataSource = new MatTableDataSource(users)
        console.log('datasrc', this.dataSource.data)
        this.dataSource.sort = this.sort
        this.loading = false
      })
      .catch((error) => {
        this._snackBar.open(error, 'Close', {
          duration: this.SNACKBAR_DURATION
        })
        this.loading = false
      })
  }

I call this function in my NgOnInit function:

  ngOnInit(): void {
    
    this.getUsers()
    
  }

The data is printed correctly into the Mat Table but if I click on the arrows of the data table to sort it nothing happens. No error is printed to the console.

I tried writing the getUsers function in the NgAfterViewInit() function I tried writing this.dataSource.sort = this.sort in the NgAfterViewInit() function (only there and I also tried writing it in both places).

I just want to be able to sort my data table.

Diunlen
  • 33
  • 4
  • `Any error is printed in the console.` -> what errors? – 馬料水碼農 Nov 15 '22 at 03:59
  • what is your expectation? Do you want to load new data from the server on sort events or do you want to sort the already existing data directly in the frontend? – Fabian Strathaus Nov 15 '22 at 07:34
  • e.g. this [SO](https://stackoverflow.com/questions/64010053/mat-paginator-of-mat-tabledoesnt-work-with-api-data/64010762#64010762). It's about mat-paginator, but same happens using mat-sort – Eliseo Nov 15 '22 at 07:45
  • @FabianStrathaus I want to sort the already existing data. – Diunlen Nov 15 '22 at 15:58

1 Answers1

0

Add into component file

import { MatSort } from '@angular/material/sort';
@ViewChild('empTbSort') empTbSort = new MatSort();

ngAfterViewInit() {
    this.empTbSort.disableClear = true;
    this.dataSource.sort = this.empTbSort;
}

Add into html file

<mat-table [dataSource]="dataSource"
                   class="mat-elevation-z8"
                   matSort
                   #empTbSort="matSort">
Parth M. Dave
  • 853
  • 1
  • 5
  • 16