typescript - 如何在 Angular 7 的 Mat-table 與分頁中設置正確的序號
我在我的 Angular7 應用程式中使用了 mat-table 並成功填充了 Firebase 資料。我想要添加一個自動遞增的序號。
我用於程式碼的 Html:
<mat-table #table2 [dataSource]="dataSource2" matSort>
<ng-container matColumnDef="sn">
<mat-header-cell *matHeaderCellDef mat-sort-header> SN. </mat-header-cell>
<mat-cell *matCellDef="let element; let i = index;">{{i+1}}</mat-cell>
</ng-container>
<ng-container matColumnDef="description">
<mat-header-cell *matHeaderCellDef mat-sort-header> Description </mat-header-cell>
<mat-cell *matCellDef="let item"> {{item.description}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" [pageSize]="5" showFirstLastButtons></mat-paginator>
分頁問題
- 當我翻到下一頁時,索引會從一重新開始。
- 如果我每頁顯示 5 個項目,那麼翻到下一頁時,它會從 1 開始,而不是從 6 開始。
答案#1
要讓索引更新到下一頁……我們做如下操作:
( [pageIndex] X [pageSize] ) + ( [rowIndex] + 1 )... 在我們的程式碼中,相當於以下內容:
<mat-table #table2 [dataSource]="dataSource2" matSort>
<ng-container matColumnDef="description">
<mat-header-cell *matHeaderCellDef mat-sort-header> Description </mat-header-cell>
<mat-cell *matCellDef="let item; let j = index">
{{ (j+1) + (myPaginator.pageIndex * myPaginator.pageSize) }} -
{{item.description}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<mat-paginator #myPaginator [length]="25"
[pageSize]="5"
[pageSizeOptions]="[5, 10, 25, 100]">
</mat-paginator>
你可以在這裡查看可運行的 StackBlitz 示範
