這份簡明指南可幫助 Angular 開發人員利用 Angular Material 函式庫。客戶請求特定功能:在所有 MatTable 上方和下方顯示 (Mat)Paginator。
挑戰:MatPaginator 只能連結到單一資料來源。
最初的嘗試涉及使用模板來渲染分頁器兩次,但這被證明是不成功的;第二個分頁器仍然不起作用。 考慮過實現與伺服器端分頁類似的自訂分頁邏輯,但由於需要跨多個頁面進行大量修改,因此被認為是不切實際的。 同步第二個分頁器的訊號實驗也失敗了。 下面介紹的解決方案提供了更直接的方法。
實作
範本:
<code class="language-html"><mat-paginator [pageSize]="50"></mat-paginator> <table mat-table>...</table> <mat-paginator (page)="pageChanged($event)"></mat-paginator></code>
組件:
<code class="language-typescript">import { Component, AfterViewInit, ViewChild, Input } from '@angular/core'; import { MatPaginator, PageEvent } from '@angular/material/paginator'; import { MatTableDataSource } from '@angular/material/table'; import { effect } from '@angular/core'; @Component(/* ... */) export class DocumentListComponent implements AfterViewInit { @Input() documents!: any[]; // input of the data; Use a more specific type if possible. dataSource = new MatTableDataSource<any>(); // dataSource of the table; Use a more specific type if possible. @ViewChild(MatPaginator, { static: true }) paginator!: MatPaginator; constructor() { effect(() => this.dataSource.data = this.documents); } ngAfterViewInit(): void { this.dataSource.paginator = this.paginator; } pageChanged(event: PageEvent): void { this.dataSource.paginator!.pageIndex = event.pageIndex; this.dataSource.paginator!._changePageSize(event.pageSize); } }</code>
說明
主要的 MatTable 和 MatPaginator 是作為標準實現的。 連接是在 ngAfterViewInit()
鉤子內建立的。
由於第二個分頁器不會自動更新,因此它的屬性源自第一個分頁器,後者管理表資料。 pageChanged()
方法處理來自底部分頁器的分頁事件,相應地更新第一個分頁器和 dataSource
。 請注意非空斷言運算子 (!
) 的使用,它假定 dataSource.paginator
在 ngAfterViewInit
之後可用。 考慮為生產代碼添加錯誤處理。 另外,將 any
替換為特定類型以獲得更好的類型安全性。
以上是將多個 MatPaginator 新增到相同資料來源的詳細內容。更多資訊請關注PHP中文網其他相關文章!