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

如何在Angular中为多个mat-table绑定不同的dataSource渲染多组数据

问题根源

你当前代码中每次请求完员工数据都会覆盖同一个dataSource变量,导致最终只能保留最后一个请求的数据源,且分页器仅绑定了一个实例,无法适配多个表格的分页需求。


解决步骤

1. 修改component.ts代码

首先导入必要依赖并声明新变量:

import { ViewChildren, QueryList } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';

// 类内部声明变量
public dataSources: {groupId: any, dataSource: MatTableDataSource<any>}[] = [];
@ViewChildren(MatPaginator) paginators!: QueryList<MatPaginator>;
public displayedColumns: string[] = ['#', 'username', 'action'];

修改业务逻辑方法:

Groups(){
  this.apiSvc.Cards().subscribe((rsp: any) => { 
    this.groups = rsp;
    // 清空旧数据源避免重复渲染
    this.dataSources = [];
    this.groups.forEach((row: any) =>{
      this.Employees(row.id);
    });
  });
}

Employees(id:any){
  this.apiSvc.Groups(id).subscribe((rsp: any) => { 
    const ds = new MatTableDataSource(rsp);
    this.dataSources.push({
      groupId: id,
      dataSource: ds
    });
  });
}

// 视图初始化后绑定分页器
ngAfterViewInit() {
  // 监听分页器实例变化,自动绑定对应数据源
  this.paginators.changes.subscribe(() => {
    this.dataSources.forEach((item, index) => {
      const targetPaginator = this.paginators.toArray()[index];
      if(targetPaginator) item.dataSource.paginator = targetPaginator;
    })
  })
}

// ngFor性能优化方法
trackByGroupId(index: number, item: any): any {
  return item.groupId;
}

2. 修改component.html代码

用*ngFor遍历数据源数组,每个元素对应渲染一套完整的表格结构:

<div *ngFor="let item of dataSources; trackBy: trackByGroupId" fxFlex.gt-lg="75" fxFlex.gt-md="73" fxFlex.gt-xs="100" fxFlex="100">
  <mat-card class="mat-card-employee">
    <mat-card-content>
      <div class="table-responsive">
        <table mat-table [dataSource]="item.dataSource" class="table employee-list no-wrap">

          <ng-container matColumnDef="#">
            <th mat-header-cell *matHeaderCellDef> ID </th>
            <td mat-cell *matCellDef="let element"> {{element.id}} </td>
          </ng-container>

          <ng-container matColumnDef="username">
            <th mat-header-cell *matHeaderCellDef> User </th>
            <td mat-cell *matCellDef="let element"> {{element.username}} </td>
          </ng-container>
          
          <ng-container matColumnDef="action">
            <th mat-header-cell *matHeaderCellDef> Actions </th>
            <td mat-cell *matCellDef="let element" class="action-link">
              <a (click)="openDialog('Update',element)" class="m-r-10 cursor-pointer"><i class="fa fa-pencil"></i></a>
              <a (click)="openDialog('Delete',element)" class="m-r-10 cursor-pointer">
                <i class="fa fa-trash text-danger"></i>
              </a>
            </td>
          </ng-container>

          <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
        </table>
        <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
      </div>
    </mat-card-content>
  </mat-card>
</div>

如果需要展示对应分组的名称,可在存入dataSources时把分组信息一起存入,在循环中直接调用即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 07:06:03