如何在Ng Bootstrap中使用Angular DataSource?
Ng Bootstrap 表格数据管理的参考与示例
基础表格结合分页、排序、筛选的实现方案
Ng Bootstrap没有像Angular Material那样封装好的DataSource类,但可以结合Angular基础特性,实现相同的数据管理逻辑:
1. 分页实现
利用Ng Bootstrap的NgbPagination组件,配合数组切片控制显示数据:
// 组件类代码 currentPage = 1; pageSize = 10; totalItems = 0; filteredData: any[] = []; originalData: any[] = []; // 存储原始数据源 // 分页切换时更新显示数据 onPageChange(page: number) { this.currentPage = page; const startIndex = (page - 1) * this.pageSize; this.filteredData = this.originalData.slice(startIndex, startIndex + this.pageSize); }
模板代码:
<table class="table table-striped"> <thead> <tr> <th>ID</th> <th>名称</th> </tr> </thead> <tbody> <tr *ngFor="let item of filteredData"> <td>{{item.id}}</td> <td>{{item.name}}</td> </tr> </tbody> </table> <ngb-pagination [(page)]="currentPage" [pageSize]="pageSize" [collectionSize]="totalItems" (pageChange)="onPageChange(currentPage)" ></ngb-pagination>
2. 排序功能
通过表头点击触发排序逻辑,修改数据顺序:
// 组件类代码 sortKey = 'id'; sortDirection = 'asc'; sortData(key: string) { if (this.sortKey === key) { this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc'; } else { this.sortKey = key; this.sortDirection = 'asc'; } this.filteredData = [...this.filteredData].sort((a, b) => { if (a[this.sortKey] < b[this.sortKey]) { return this.sortDirection === 'asc' ? -1 : 1; } if (a[this.sortKey] > b[this.sortKey]) { return this.sortDirection === 'asc' ? 1 : -1; } return 0; }); }
模板表头修改:
<th (click)="sortData('id')"> ID <span *ngIf="sortKey === 'id'"> {{sortDirection === 'asc' ? '↑' : '↓'}} </span> </th> <th (click)="sortData('name')"> 名称 <span *ngIf="sortKey === 'name'"> {{sortDirection === 'asc' ? '↑' : '↓'}} </span> </th>
3. 筛选功能
结合Angular表单控件实现实时筛选:
// 组件类代码,需引入FormControl import { FormControl } from '@angular/forms'; filterControl = new FormControl(''); ngOnInit() { this.filterControl.valueChanges.subscribe(value => { this.applyFilter(value); }); } applyFilter(filterValue: string) { const filter = filterValue.toLowerCase(); this.filteredData = this.originalData.filter(item => item.name.toLowerCase().includes(filter) || item.id.toString().includes(filter) ); this.totalItems = this.filteredData.length; this.currentPage = 1; // 筛选后重置页码到第一页 this.onPageChange(this.currentPage); }
模板添加筛选框:
<input type="text" class="form-control mb-3" [formControl]="filterControl" placeholder="搜索ID或名称">
官方参考方向
- Ng Bootstrap官方文档的Pagination组件示例,包含基础分页、自定义页码等场景,可直接复用逻辑到表格中
- Ng Bootstrap的Dropdown组件可扩展用于多条件筛选菜单
- Angular官方文档中
*ngFor、表单控件的基础教程,是实现这些功能的核心基础
内容的提问来源于stack exchange,提问作者Fadly Dzil
相关产品推荐
相关产品推荐

