在mat-table parent中使用ngif时,mat-filtering/mat-sort无法正常工作

ave*_*che 8 angular-material angular angular6

请注意,分页/排序无法正常工作.分页不显示它显示的元素数量,并且排序不起作用,但是如果删除html文件中的行*ngIf ="dataSource?.filteredData.length> 0",则错误是固定的.如果您使用过滤,它可以工作,但它不会显示过滤器数量

检查示例.

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

yer*_*yer 19

在component.ts中,替换此代码

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

ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
}
Run Code Online (Sandbox Code Playgroud)

有了这个 :

  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;
  }
Run Code Online (Sandbox Code Playgroud)

在你的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>
Run Code Online (Sandbox Code Playgroud)

  • 您能解释一下为什么可以解决此问题吗? (5认同)
  • 在 Angular 9+ 中,`@ViewChild(MatSort, {static: false}) 排序:MatSort; @ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;` 并保持 ngAfterViewInit 与答案中的相同。 (2认同)

Rut*_*hah 7

这可以通过以下策略解决:

dataSource = new MatTableDataSource();

@ViewChild(MatSort, {static: false}) set content(sort: MatSort) {
  this.dataSource.sort = sort;
}
Run Code Online (Sandbox Code Playgroud)

现在,即使您使用 *ngIf,它也会起作用。

  • 对于任何寻求更多解释的人来说,[这个答案](/sf/answers/3945172871/) 会有所帮助;`{ static: false }` 选项适用于 Angular 8+ (2认同)