带有多个动态垫表的垫分页器

问题描述 投票:0回答:1

在我的组件页面中,我有一个基于 API 响应动态生成的 mat-table(因此选项卡可以从 1 到 n)。 在每个选项卡中,我都有一个 mat-table,其中包含始终来自 API 的数据。 我设置排序和分页如下:

component.ts:

dataSource: MatTableDataSource<Interface>;
@ViewChild('MatPaginatorAS') paginatorAS: MatPaginator | null;
@ViewChild('MatSortAS') sortAS: MatSort | null;
displayedColumnsAs: string [] = ['id']
//Each time I change tabs a function re-executes these commands:
this.dataSource = new MatTableDataSource(res);
this.dataSource.sort = this.sortAS;
this.dataSource.paginator = this.paginatorAS;

component.html:

<mat-tab-group animationDuration="0ms">
   <mat-tab *ngFor="let Phase of Phases; let index = index" [label]="phaseName">
     <table #MatSortAS="matSort" mat-table [dataSource]="dataSource" matSort>
       <ng-container matColumnDef="id">
        <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
         <td mat-cell *matCellDef="let el">
          {{el.name}}
         </td>
       </ng-container>
      <tr mat-header-row *matHeaderRowDef="displayedColumnsAs"></tr>
      <tr mat-row *matRowDef="let el; columns: displayedColumnsAs;"></tr>
     </table>
     <mat-paginator #MatPaginatorAS="matPaginator" [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
   </mat-tab>
</mat-tab-group>

但在第一个选项卡中它有效,而在所有其他选项卡中它不起作用并保持在第一个选项卡中选择的设置。 我不能为每个选项卡的排序和分页指定不同的名称,因为我不知道有多少,因为它们是由 API 动态生成的。

angular typescript angular-material
1个回答
0
投票

如果我正确理解你的问题:你有一个 API 正在交付 1..n 阶段(在你的 *ngFor 循环中使用的名称)显示为选项卡。点击选项卡时,相应的数据将从 API 加载,并应显示在 mat-table 中。

在您的 HTML 中,您正在为每个表/选项卡生成多个带有 matSort 和 matPaginator 的 mat-table。因此,在初始化视图后,您将拥有多个 matSorts 和 matPaginators,因此您需要按以下方式处理分页器(以及相应的 matSorts):

@ViewChildren(MatPaginatorAS) paginators = new QueryList<MatPaginator>();

此对象将包含您视图中的所有分页器。 初始化数据源时,您需要引用在当前可见/单击的选项卡中创建的分页器。

即:您想在选项卡 2 中初始化数据源:

setTimeout(() => {if (!!this.paginators.get(tabIndex)) this.serviceorders[tabIndex].paginator = this.paginators.get(tabIndex)!;}, 200);

Add-On:我最近有一个非常相似的设置,我通过为每个选项卡初始化一个唯一的 matTableDataSource(存储在数组或 dto-object 中)并在初始化后立即为每个选项卡分配分页器来实现更好的性能,而不是每次单击选项卡时都是新的。

没有测试代码片段,但我希望它能有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.