【问题标题】:mat-filtering/mat-sort not work correctly when use ngif in mat-table parent在 mat-table 父级中使用 ngif 时,mat-filtering/mat-sort 无法正常工作
【发布时间】:2018-06-08 19:52:38
【问题描述】:

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

检查示例。

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

【问题讨论】:

  • 你想要那个 *ngIf 条件吗?
  • @yer hi!,是的,我需要它在没有结果时隐藏表格并显示另一条消息
  • 你可以用这个 *ngIf="dataSource?.filteredData" 代替。
  • @yer 工作!但不完全正确。我用另一个链接更新了示例
  • 你能告诉现在什么工作不正常吗?

标签: angular angular-material angular6


【解决方案1】:

在你的component.ts中,替换这段代码

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

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

用这个:

  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;
  }

在你的 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>

【讨论】:

  • 在 Angular 9+ 中,@ViewChild(MatSort, {static: false}) sort: MatSort; @ViewChild(MatPaginator, {static: false}) paginator: MatPaginator; 并保持 ngAfterViewInit 与答案中的相同。
  • 谁能解释为什么在使用 mat-table*ngIf 时必须这样做,而不是组件中已经存在的内容?
  • 感谢您的回答。这在 mat-table 中对我有用。我刚刚投票了
【解决方案2】:

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

dataSource = new MatTableDataSource();

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

现在即使你使用 *ngIf,它也可以工作。

【讨论】:

  • 对于任何寻求更多解释的人,this answer 会有所帮助; { static: false } 选项适用于 Angular 8+
  • 最佳答案,仍在使用 Angular 13
【解决方案3】:

只需添加静态:假而不是真,工作正常 @ViewChild(MatSort, {static: false})e }) public sortaddEpisode: MatSort;

【讨论】:

  • 只需添加 static: false 即可。 @ViewChild(MatSort, {static: false}) matSort: MatSort;
【解决方案4】:

我在使用 *ngIf 隐藏 mat-paginator 时遇到了问题,因此我使用以下解决方法修复了它。在global.scss 中定义以下样式,并在 mat-paginator 中有条件地应用此样式

.hide-paginator {
  display: none !important;
}

<mat-paginator 
[length]="totalElements"
      [pageSize]="searchDefinition.size" [pageSizeOptions]="paginationOptions" 
      [ngClass]="{'hide-paginator': data.length <= 0 }">
</mat-paginator>
  

【讨论】:

    【解决方案5】:

    在您的html代码中添加&lt;tr&gt;标签并添加mat-sort-header="fieldname"即可解决。

    【讨论】:

      猜你喜欢
      • 2020-11-17
      • 2018-07-21
      • 2018-11-07
      • 2020-06-19
      • 1970-01-01
      • 2019-09-25
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多