Angular 自定义表格如何绑定 ngb-pagination 实现可交互分页功能
ngb-pagination 分页绑定实现步骤
1. 组件TS文件调整
先在对应组件的逻辑文件中定义分页相关变量,以及数据截取方法:
import { Component, OnInit } from '@angular/core'; @Component({ // 保留你原有的组件配置即可 }) export class YourComponent implements OnInit { // 存储全量表格原始数据 originalData: any[] = []; // 分页后用于表格渲染的当前页数据 paginatedData: any[] = []; // 当前页码,默认展示第一页 currentPage = 1; // 每页展示数据条数,和分页组件的pageSize保持一致 pageSize = 2; ngOnInit(): void { // 此处替换为你自己的数据源获取逻辑 this.originalData = [/* 你的全量表格数据 */]; // 初始化加载第一页数据 this.loadPaginatedData(); } // 分页数据更新方法 loadPaginatedData(): void { // 计算当前页数据的起始下标 const startIndex = (this.currentPage - 1) * this.pageSize; // 截取对应区间的数据作为表格渲染源 this.paginatedData = this.originalData.slice(startIndex, startIndex + this.pageSize); } }
2. 模板文件调整
需要修改两个核心点:分页组件增加交互绑定、表格遍历分页后的数据,修改后的完整代码如下:
<div class="table-responsive"> <table id="recent-orders" class="table table-hover table-xl mb-0"> <thead> <tr> <th class="border-top-0">Status</th> <th class="border-top-0">Invoice#</th> <th class="border-top-0">Customer Name</th> <th class="border-top-0">Categories</th> <th class="border-top-0">Shipping</th> <th class="border-top-0">Amount</th> <th class="border-top-0">Action</th> </tr> </thead> <tbody> <!-- 遍历分页后的当前页数据 --> <tr *ngFor="let x of paginatedData"> <td class="text-truncate"><i class="fa fa-dot-circle-o success font-medium-1 mr-1"></i> Paid</td> <td class="text-truncate"><a href="#">{{ x.invoice }}</a></td> <td class="text-truncate"> <span>{{ x.name }}</span> </td> <td> <button type="button" class="btn btn-sm btn-outline-danger round">{{ x.Category }}</button> </td> <td> <ngb-progressbar type="danger" [value]="25" [striped]="true" class="progress-bar-md bg-gradient-x-danger"></ngb-progressbar> </td> <td class="text-truncate">$ {{ x.price }}</td> <td> <a class="success p-0" data-original-title="" title=""> <i class="fa fa-pencil font-medium-3 mr-2"></i> </a> <a class="info p-0" data-original-title="" title=""> <i class="fa fa-check font-medium-3 mr-2"></i> </a> <a class="danger p-0" data-original-title="" title=""> <i class="fa fa-trash-o font-medium-3 mr-2"></i> </a> </td> </tr> </tbody> </table> <!-- 新增页码双向绑定、页码变更事件、总条数绑定全量数据长度 --> <ngb-pagination [collectionSize]="originalData.length" [pageSize]="pageSize" [maxSize]="7" [rotate]="true" [(page)]="currentPage" (pageChange)="loadPaginatedData()" ></ngb-pagination> </div>
如果你的数据是通过后端接口分页获取,只需要把loadPaginatedData方法里的本地截取逻辑替换为对应页码的接口请求逻辑即可,其余绑定规则不变。
内容的提问来源于stack exchange,提问作者Umaiz Khan
相关产品推荐
相关产品推荐

