mat-filtering/mat-sort not work correctly when use ngif in mat-table parent

This can be solved by the following strategy:

dataSource = new MatTableDataSource();

@ViewChild(MatSort, {static: false}) set content(sort: MatSort) {
  this.dataSource.sort = sort;
}

Now even if you use *ngIf, it will work.


In your component.ts, replace this code

@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;

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

with this :

  private paginator: MatPaginator;
  private sort: MatSort;


  @ViewChild(MatSort) set matSort(ms: MatSort) {
    this.sort = ms;
    this.setDataSourceAttributes();
  }

  @ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
    this.paginator = mp;
    this.setDataSourceAttributes();
  }

  setDataSourceAttributes() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

And in your html:

    <mat-card *ngIf="!dataSource?.filteredData.length" style="margin-bottom: 5px">
        <div><span>ZERO RESULT</span></div>
    </mat-card>

    <mat-card *ngIf="dataSource?.filteredData.length">
    ** insert the table code that you have **
    </mat-card>

Just adding static:false instead true, working fine @ViewChild(MatSort, {static: false})e }) public sortaddEpisode: MatSort;