Angular 16实现数据表格全分页搜索过滤而非仅当前页
解决NgxPagination全表搜索过滤问题
问题根源
你当前的过滤逻辑是先分页、后过滤,导致搜索仅对当前页数据生效。需要调整执行顺序为先过滤全量数据、后分页,同时动态更新分页的总条目数。
方案一:组件内维护过滤后数据(推荐,性能更优)
1. 修改组件类代码
添加filteredMatters变量存储过滤后的数据,新增过滤方法并在数据加载、搜索文本变化时触发:
export class AllMattersComponent { isLoading: boolean = false; response: boolean = false; Matters: any[] = []; // 原始全量数据 filteredMatters: any[] = []; // 过滤后的数据 page: number = 1; count!: number; pageSize: number = 10; pageSizes = [10, 50, 100, 150, 250]; searchText = ''; ngOnInit(): void { this.loadMatters(); } loadMatters(){ this.apiservice.viewMatters().subscribe((res: any) => { if(res.status === 200){ this.response = true; this.isLoading = false; // 处理原始数据并初始化过滤结果 this.Matters = res.results.map(matter => ({ ...matter, client_name: matter.client_person?.full_name || matter.client_company?.company_name || '' })); this.count = res.count; this.filterMatters(); } else if (res.status === 400){ this.showError(res.results.error); this.response = true; this.isLoading = false; } }); } // 执行搜索过滤 filterMatters() { const searchTerm = this.searchText.trim().toLowerCase(); if (!searchTerm) { this.filteredMatters = [...this.Matters]; return; } // 全字段匹配(可修改为指定字段优化性能) this.filteredMatters = this.Matters.filter(item => JSON.stringify(item).toLowerCase().includes(searchTerm) ); this.page = 1; // 搜索后重置到第一页 } }
2. 修改搜索栏模板
添加ngModelChange事件触发过滤:
<div class="d-flex align-items-center position-relative my-1"> <i class="ki-outline ki-magnifier fs-3 position-absolute ms-5"></i> <input type="text" data-kt-customer-table-filter="search" class="form-control w-250px ps-12 me-3" placeholder="Search..." [(ngModel)]="searchText" (ngModelChange)="filterMatters()"> </div>
3. 修改表格分页模板
使用过滤后的数据进行分页,动态绑定总条目数:
<tbody class="fw-semibold text-gray-600"> <tr class="odd" *ngFor="let matter of filteredMatters | paginate: { itemsPerPage: pageSize, currentPage: page, totalItems: filteredMatters.length }"> <!-- 表格内容 --> </tr> </tbody>
方案二:模板内调整管道顺序(快速实现,性能略差)
直接修改模板中管道的执行顺序,让过滤先于分页,并动态计算过滤后的总条目数:
<tbody class="fw-semibold text-gray-600"> <tr class="odd" *ngFor="let matter of Matters | searchFilter: searchText | paginate: { itemsPerPage: pageSize, currentPage: page, totalItems: (Matters | searchFilter: searchText).length }"> <!-- 表格内容 --> </tr> </tbody>
注意:此方式会让
searchFilter管道执行两次,数据量大时可能影响性能。
性能优化建议
如果数据量较大,不建议用JSON.stringify做全字段匹配,可指定具体搜索字段提升效率:
// 替换filterMatters中的过滤逻辑 this.filteredMatters = this.Matters.filter(item => item.client_name.toLowerCase().includes(searchTerm) || item.matter_number?.toLowerCase().includes(searchTerm) || // 示例字段 item.status?.toLowerCase().includes(searchTerm) // 示例字段 );
内容的提问来源于stack exchange,提问作者CoderS
相关产品推荐
相关产品推荐

