You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular的mat-table中添加加载状态组件

实现Angular Mat-Table加载状态的方案

方案一:加载提示行(轻量型)

  1. 在组件类中定义加载状态变量,控制加载提示的显示/隐藏:
isLoading = true;
dataSource = new MatTableDataSource();

ngOnInit() {
  this.loadTableData();
}

loadTableData() {
  // 发起API请求
  this.yourApiService.fetchData().subscribe({
    next: (response) => {
      this.dataSource.data = response;
      this.isLoading = false;
    },
    error: () => {
      this.isLoading = false;
    }
  });
}
  1. 修改表格模板,添加加载状态行(优先级高于空数据行):
<table mat-table [dataSource]="dataSource" matSort class="table table-responsive">
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>

  <!-- 加载状态行 -->
  <tr class="mat-row" *ngIf="isLoading">
    <td class="mat-cell text-center" [attr.colspan]="displayedColumns.length">
      <mat-spinner diameter="30"></mat-spinner>
      <span class="ms-2">加载中...</span>
    </td>
  </tr>

  <!-- 原有空数据行 -->
  <tr class="mat-row" *matNoDataRow>
    <td class="mat-cell text-center" [attr.colspan]="displayedColumns.length">
      No data to display.
    </td>
  </tr>
</table>

注意:需要确保MatProgressSpinnerModule已导入到你的模块中。

方案二:表格覆盖层加载(突出型)

如果需要更明显的加载提示,可以给表格添加半透明覆盖层:

  1. 模板结构调整:
<div class="table-wrapper position-relative">
  <table mat-table [dataSource]="dataSource" matSort class="table table-responsive">
    <!-- 表格原有内容 -->
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    <tr class="mat-row" *matNoDataRow>
      <td class="mat-cell text-center" [attr.colspan]="displayedColumns.length">
        No data to display.
      </td>
    </tr>
  </table>

  <!-- 加载覆盖层 -->
  <div *ngIf="isLoading" class="loading-overlay">
    <mat-spinner diameter="40"></mat-spinner>
  </div>
</div>
  1. 添加对应CSS样式:
.table-wrapper {
  position: relative;
  min-height: 200px; /* 保证覆盖层有足够高度 */
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

内容的提问来源于stack exchange,提问作者Dishant Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 20:12:16