如何为ThingsBoard自定义组件的Angular Material表格添加分页功能
ThingsBoard自定义Angular Material表格添加分页功能方案
1. 修改HTML代码
你需要把原表格的数据源绑定调整,同时在表格下方添加<mat-paginator>分页控件,修改后完整代码如下:
<mat-table [dataSource]="dataSource" id="reportTable" style="background-color:inherit;"> <ng-container *ngFor="let column of tableMeta" [matColumnDef]="column.key"> <mat-header-cell *matHeaderCellDef [style.background-color]="settings?.tableHeaderBgColor" [style.color]="settings?.tableHeaderTxtColor">{{column.title}} </mat-header-cell> <mat-cell *matCellDef="let element" style="color:inherit;"> {{element[column.key]}} </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns" [style.background-color]="settings?.tableHeaderBgColor"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> <!-- 新增分页控件 --> <mat-paginator #paginator [pageSize]="10" [pageSizeOptions]="[5, 10, 20, 50]" [showFirstLastButtons]="true" style="background-color: inherit;"> </mat-paginator>
参数可按需调整:
pageSize:默认每页显示条数pageSizeOptions:可选的每页条数下拉选项showFirstLastButtons:是否显示跳转到首页/尾页的按钮
2. 修改JavaScript逻辑
你需要把普通数组类型的数据源替换为Angular Material内置的MatTableDataSource实例,同时绑定分页器,修改后完整代码如下:
let $scope = self.ctx.$scope; // ThingsBoard已内置Angular Material相关依赖,直接调用即可 const { MatTableDataSource } = window['@angular/material/table']; $scope.tableMeta=[{'title':'Date', 'key':'date'},{'title':'Online', 'key':'online'}, {'title':'Running', 'key': 'running'}, {'title':'Stopped', 'key': 'stopped'}, {'title':'Offline', 'key': 'offline'}]; $scope.displayedColumns=['date', 'online', 'running', 'stopped', 'offline']; // 初始化数据源实例 $scope.dataSource = new MatTableDataSource([]); // 等待视图渲染完成后绑定分页器 setTimeout(() => { $scope.dataSource.paginator = $scope.paginator; $scope.$apply(); }, 0); // 你的数据赋值逻辑,拿到全量数据后直接更新到数据源即可自动分页 const fullTableData = []; // 替换为你的实际全量数据集 $scope.dataSource.data = fullTableData;
如果你的数据是异步请求获取的,在拿到数据的回调里给$scope.dataSource.data赋值即可,分页逻辑会自动生效,不需要额外手动计算分页数据。
内容的提问来源于stack exchange,提问作者Mohammad Nasir
相关产品推荐
相关产品推荐

