Mat-sort is not working in angular mat-table

AbhiRam picture AbhiRam · Feb 26, 2019 · Viewed 9k times · Source

My mat-table is working fine, but when adding mat-sort following the official api documentation, it fails at the ngAfterViewInit with the following message

Cannot set property 'sort' of undefined aq LeadsComponent.push../src/app/leads/leads.component.ts.LeadsComponent.ngAfterViewInit

There is already a SO post on Mat-table Sorting Demo and tried them but I still am not able to get it working.

can some one hemp me solve this issue? The official example works with a "static" MatTableDataSourcedefined in the component itself, I am querying from my back-end, however.

MatSortModule is already imported in app.module.ts, mat-sort-header directives are applied to the columns and the ngAfterViewInit is already exactly like in the official example...

 export class LeadsComponent implements OnInit,AfterViewInit  {

  displayedColumns: string[] = ['name', 'leadStatus', 'mobile', 'email', 'actions'];
  dataSource: MatTableDataSource<LeadsChildObject>;
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(public dialog: MatDialog, private dashBoardService: LeadsService,
    private toast: ToastrService) {
  }

    ngAfterViewInit() {
        this.dataSource.sort = this.sort;
      }

      ngOnInit() {
        this.dashboardService.getFeedback.subscribe(
          res => {
            this.leadlist= res;
            this.dataSource = new MatTableDataSource(this.leadlist);
          }
        );
      }
    }
}

Answer

Julien Ambos picture Julien Ambos · Feb 26, 2019

Cannot set property 'sort' of undefined aq LeadsComponent.push../src/app/leads/leads.component.ts.LeadsComponent.ngAfterViewInit

This error refers to "sort" being called on an undefined property, which, after your update, is the datasource property, because you don't initialize it.

It is not initialized, because your subscribe() (where you initialize it) is async, therefore, the initialization happens after ngAfterViewInit() happens.

Please initialize it in your ngOnInit() with:

ngOnInit() {
  // This line of code below:
  this.dataSource = new MatTableDataSource<LeadsChildObject>();

  this.dashboardService.getFeedback.subscribe(
    res => {
      this.leadlist= res;
      this.dataSource = new MatTableDataSource(this.leadlist);
      this.dataSource.sort = this.sort;
    }
  );
}

The problem in your approach ist, that you are mistaking the use of the MatTableDataSource with a plain array approach (Simple Table approach). Please find this documentation to implement the MatTableDataSource approach