如何在Angular分页中隐藏最后一页页码?基于ngx-pagination定制
定制ngx-pagination实现指定分页样式
要实现你需要的<< < 1 2 3 ... > >>或<< < ... 7 8 9 ... > >>样式,核心是利用ngx-pagination的自定义模板功能,重写分页结构并控制页码的显示逻辑,避免展示最后一页的数字。
步骤1:基础配置(确保已引入模块)
如果你还没配置ngx-pagination,先在模块中导入:
import { NgxPaginationModule } from 'ngx-pagination'; @NgModule({ imports: [NgxPaginationModule] }) export class YourModule { }
步骤2:自定义分页模板
在组件模板中使用<pagination-template>指令,完全自定义分页的UI结构和交互逻辑:
<div class="custom-pagination"> <pagination-template #p="pagination-template" [pageSize]="itemsPerPage" [totalItems]="totalItems" (pageChange)="currentPage = $event"> <!-- 首页按钮 << --> <button (click)="p.firstPage()" [disabled]="p.currentPage === 1">«</button> <!-- 上一页按钮 < --> <button (click)="p.previousPage()" [disabled]="p.currentPage === 1">‹</button> <!-- 显示首页页码(当当前页离首页足够远时) --> <button *ngIf="p.currentPage > 3" (click)="p.setPage(1)">1</button> <!-- 前省略号(当当前页离首页足够远时) --> <span *ngIf="p.currentPage > 3">...</span> <!-- 显示当前页附近的页码(排除最后一页) --> <button *ngFor="let page of getVisiblePages(p.currentPage, p.totalPages)" (click)="p.setPage(page)" [class.active]="page === p.currentPage"> {{page}} </button> <!-- 后省略号(当当前页离尾页足够远时) --> <span *ngIf="p.currentPage < p.totalPages - 2">...</span> <!-- 下一页按钮 > --> <button (click)="p.nextPage()" [disabled]="p.currentPage === p.totalPages">›</button> <!-- 尾页按钮 >> --> <button (click)="p.lastPage()" [disabled]="p.currentPage === p.totalPages">»</button> </pagination-template> </div>
步骤3:实现页码显示逻辑
在组件类中添加getVisiblePages方法,用来计算需要展示的页码范围(当前页前后各1页,且不包含最后一页):
import { Component } from '@angular/core'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent { currentPage = 1; itemsPerPage = 10; totalItems = 100; // 替换为你的实际总数据条数 getVisiblePages(current: number, totalPages: number): number[] { const pages = []; // 计算页码范围:当前页前后各1页,同时确保不小于1、不大于总页数-1(排除最后一页) const startPage = Math.max(1, current - 1); const endPage = Math.min(totalPages - 1, current + 1); for (let i = startPage; i <= endPage; i++) { pages.push(i); } return pages; } }
步骤4:自定义样式
添加CSS样式让分页看起来更美观,匹配你的需求:
.custom-pagination button { margin: 0 4px; padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px; background-color: #fff; cursor: pointer; font-size: 14px; } .custom-pagination button.active { background-color: #007bff; color: #fff; border-color: #007bff; } .custom-pagination button:disabled { opacity: 0.5; cursor: not-allowed; } .custom-pagination span { margin: 0 4px; color: #6c757d; font-size: 14px; }
调整说明
- 如果需要显示更多附近页码(比如当前页前后2页),只需修改
getVisiblePages中的current - 1和current + 1为current - 2和current + 2即可。 - 若不需要尾页按钮(
>>),直接删除对应的按钮元素即可。 - 样式部分可根据项目设计规范自由调整。
内容的提问来源于stack exchange,提问作者CodingSS
相关产品推荐
相关产品推荐

