mat-sort not working on mat-table

Problem is that next piece of code

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

is happen before you actually got your table in subscription here:

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

  }

As a possible solution, you could synchronize ngAfterViewInit call and getFeedback subscription via Observable.zip. Please refer to RxJS zip documentation


The simple solution for this is instead of declaring sorting in ngAfterViewInit, declare after you get the result from the "this._feedbackService.getFeedback.subscribe".

The solution is as below.

  ngOnInit() {
    this._feedbackService.getFeedback.subscribe(
      res => {
        this.feedbacks = res;
        this.dataSource = new MatTableDataSource(this.feedbacks);

        this.dataSource.sort = this.sort; //this will solve your problem

      }
    );

  }

The above one works perfectly for me.

Thanks,


For matSort to work the type defination is important, at least that's what I found. So with type as any in the code : dataSource: MatTableDataSource; it will not work. There has to be a type defined here to make it work, try to define a interface and pass it in the generics of MatTableDataSource . Also matColumnDef has to match the property name of the defined type.