Angular 5 Material Data Table sorting not working

不想你离开。 提交于 2019-11-30 21:51:43

The problem you have is the *ngIf in the mat-table selector. If you check this.sort you'll see it's undefined. This works :

export class TableComponent implements OnInit { 
sort;
@ViewChild(MatSort) set content(content: ElementRef) {
  this.sort = content;
  if (this.sort){
     this.dataSource.sort = this.sort;

  }
}

I don't remember what answer here in SO I used as a guide for the solution.

This probably is because your sorter isn't correctly bound to your array.

Try using a timeout to delay the binding :

this.convertJsonResultToArray(res);
this.dataSource = new MatTableDataSource(this.eadItems);
setTimeout(() => {
  this.dataSource.paginator = this.paginator;
  this.dataSource.sort = this.sort;

});
this.showDataForm = true;

If some one still having a issue and requires cleaner approach, they can implement ngAfterViewInit interface and implement it. it's lifecycle hook that is called after Angular has fully initialized a component's view. By referencing questioner's code, TS can be updated by following code.

import { Component, OnInit, ChangeDetectorRef, ViewChild, AfterViewInit  } from '@angular/core';
...
...

export class TableComponent implements OnInit, AfterViewInit {
   ...
   ...
   ngAfterViewInit() {
      this.dataSource.sort = this.sort; // apply sort after view has been initialized.
   }

} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!