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

旧时模样 提交于 2020-01-22 12:04:18

问题


Note that paging/sort not work correctly. Paging does not show the number of elements it is showing and sorting does not work, but if you delete the line in the html file *ngIf="dataSource?.filteredData.length > 0" the error is fixed. If you use filtering, it works, but it does not show the filter amount

Check the example.

https://stackblitz.com/edit/angular-wqkekh-nm3pn2?file=app/table-pagination-example.html


回答1:


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>



回答2:


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.




回答3:


Adding <tr> tag in your html code and adding mat-sort-header="fieldname" you can get resolved.



来源:https://stackoverflow.com/questions/50767580/mat-filtering-mat-sort-not-work-correctly-when-use-ngif-in-mat-table-parent

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