首页 > 解决方案 > 如何动态显示/隐藏 mat-table 中的某些行?

问题描述

我在我的 Angular 应用程序中使用了 mat-table 组件,其中显示了一些体育赛事的结果。通常,我只想显示三个最佳结果,然后,当用户单击“省略号按钮”(如在相关图片上)时 - 表格应展开并显示其余隐藏行。我在标记中使用 *ngIf 语句时遇到问题,因为我不允许有多个带有 * 前缀的属性。如何以不同的方式做到这一点?提前致谢。

<table mat-table [dataSource]="qualifyingResults" class="exo-2">
  <ng-container matColumnDef="position">
    <th mat-header-cell *matHeaderCellDef>POS</th>
    <td mat-cell *matCellDef="let result">{{ result.position }}</td>
  </ng-container>
  <ng-container matColumnDef="driver">
    <th mat-header-cell *matHeaderCellDef class="center-header">DRIVER</th>
    <td mat-cell *matCellDef="let result" class="text-center font-weight-bold">{{ result.Driver.code }}</td>
  </ng-container>
  <ng-container matColumnDef="time">
    <th mat-header-cell *matHeaderCellDef>TIME</th>
    <td mat-cell *matCellDef="let result">{{ result.time }}</td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>

在此处输入图像描述

标签: angulartypescriptangular-material

解决方案


你可以很容易地做到这一点。在您的数据源中,仅获取前 3 个结果。然后将省略号按钮单击事件绑定到获取其余数据的函数。然后更新数据源。

像这样的东西:

dataSource: MatTableDataSource<any[]>;

ngOnInit() {
  this.getThreeResults.subscribe(
    data => this.dataSource = new MatTableDataSource(data)
  )
}

onEllipsisButtonClick() {
  this.getRestOfTheData.subscribe(
    data => this.dataSource.data = data
  )
}

推荐阅读