You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中为表格添加基于Bootstrap的分页功能?

Angular 纯前端分页实现方案(兼容Bootstrap)

所有逻辑完全在前端实现,无需修改后端Spring Boot代码,直接使用原生Bootstrap样式,适配你现有项目结构。

1. 修改组件.ts文件

先在你的组件类中添加分页相关变量和逻辑:

// 分页基础配置,可自行调整每页显示条数
pageSize = 10;
currentPage = 1;
filterTerm = '';
// 你的原学生列表变量,此处仅做示意,保留你原有定义即可
students: any[] = [];

// 过滤后的学生列表,此处过滤逻辑和你原有filter管道保持一致即可
get filteredStudents(): any[] {
  if (!this.filterTerm) return this.students;
  const term = this.filterTerm.trim().toLowerCase();
  return this.students.filter(student => 
    student.namestudent.toLowerCase().includes(term) ||
    student.codestudent.toString().toLowerCase().includes(term)
  );
}

// 分页后当前页展示的学生数据
get paginatedStudents(): any[] {
  const start = (this.currentPage - 1) * this.pageSize;
  return this.filteredStudents.slice(start, start + this.pageSize);
}

// 总页数计算
get totalPages(): number {
  return Math.ceil(this.filteredStudents.length / this.pageSize);
}

// 页码切换方法
changePage(targetPage: number): void {
  if (targetPage < 1 || targetPage > this.totalPages) return;
  this.currentPage = targetPage;
}

注意:如果你的自定义filter管道有其他过滤规则,直接替换上方filteredStudents的过滤逻辑即可,确保过滤结果和原有逻辑一致。


2. 调整HTML模板

2.1 修改表格行循环逻辑

将原有的表格行循环:

<tr *ngFor="let student of students| filter:filterTerm">

替换为:

<tr *ngFor="let student of paginatedStudents">

同时可在tbody中添加空状态提示:

<tr *ngIf="filteredStudents.length === 0">
  <td colspan="4" class="text-center">暂无匹配的学生数据</td>
</tr>

2.2 添加分页控件

在</table>标签后添加Bootstrap样式的分页组件:

<nav class="d-flex justify-content-center mt-3">
  <ul class="pagination">
    <!-- 上一页按钮 -->
    <li class="page-item" [class.disabled]="currentPage === 1">
      <button class="page-link" (click)="changePage(currentPage - 1)">上一页</button>
    </li>
    <!-- 页码按钮 -->
    <li class="page-item" *ngFor="let page of [].constructor(totalPages); let idx = index" [class.active]="currentPage === idx + 1">
      <button class="page-link" (click)="changePage(idx + 1)">{{idx + 1}}</button>
    </li>
    <!-- 下一页按钮 -->
    <li class="page-item" [class.disabled]="currentPage === totalPages">
      <button class="page-link" (click)="changePage(currentPage + 1)">下一页</button>
    </li>
  </ul>
</nav>

可选优化

如果需要支持自定义每页显示条数,可在搜索框下方添加选择器:

<div class="d-flex justify-content-end mb-2">
  <span class="me-2">每页显示:</span>
  <select class="form-select form-select-sm w-auto" [(ngModel)]="pageSize" (change)="changePage(1)">
    <option [value]="5">5条</option>
    <option [value]="10" selected>10条</option>
    <option [value]="20">20条</option>
    <option [value]="50">50条</option>
  </select>
</div>

内容的提问来源于stack exchange,提问作者a_l_e_x

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 23:57:02