【发布时间】:2018-11-15 04:25:04
【问题描述】:
我正在使用 Angular Material 数据表来显示可以添加到的对象列表。将对象添加到数据源时,页面索引会中断并显示负数。我发现解决此问题的唯一方法是将材料分页器的页面索引重置为 0。但是,对分页器的任何进一步更改都会导致 pageIndex 为 -1 或分页器损坏。这是一个例子:
我首先在 Angular Material 数据源中设置新数据,如下所示:
private refreshTable() {
// first we update the length of the paginator with the new length of the datasource data to ensure parity
this.paginator.length = this.dataSource.data.length;
// next we get the current page number so we can return to it later.
let currentPage = this.paginator.pageIndex;
this.tempSubscription2 = this.rrService.getSearchResults(this.searchEnv.outputPayload(true, true)).subscribe(
(data: any) => {
this.extractSBRs(data);
this.dataSource.data = [];
// Here is where the dataSource is reset...
this.dataSource.data = this.sbrs;
this.paginator.length = this.dataSource.data.length;
this.paginator.pageIndex = 0;
this.dataSource.paginator = this.paginator;
console.log('made it this far');
if (this.dataSource.paginator.pageIndex < currentPage) {
console.log('need to return to the current page');
this.paginator.pageIndex = currentPage;
this.paginator._pageIndex = currentPage;
this.dataSource.paginator.pageIndex = currentPage;
this.dataSource.paginator._pageIndex = currentPage;
}
},
(err: any) => {
},
() => {
}
);
}
运行此代码时,从第一页开始更新就可以了,因为 this.paginator.pageIndex 被设置为 0。一旦在大于零的页面上添加元素,表格将显示第一页,分页器有pageIndex 为 -1,UI 中的分页器如下所示:
注意负索引-9 - 0。似乎很少有更新 Angular Material Data Table 的示例,甚至更少有关于更新它们如何影响 Angular Material 分页器的进一步说明。如何让分页器转到 0 以外的 pageIndex 而不会出现负索引问题?
我尝试只更新this.paginator,它是根据here 的建议通过ViewChild() 获取的。我还尝试更新您可以在上面的代码中看到的dataSource.paginator。
这是我的导入:
import {
AfterContentInit, AfterViewInit, ApplicationRef, ChangeDetectorRef,
Component, OnDestroy, OnInit,
ViewChild
} from '@angular/core';
import { SearchEnvironment } from "../classes/search-environment";
import { SearchFilterDropdown } from "../classes/search-filter-dropdown";
import { ActivatedRoute, Router } from "@angular/router";
import {MatTableDataSource, MatPaginator, MatDialog, MatTable, MatSnackBar} from "@angular/material";
import { RemoteRetrievalService } from "../core/services/remote-retrieval.service";
import { Observable } from "rxjs/Observable";
如何在不导致 paginator.pageIndex 值中的负索引或项目范围内的负值的不良用户体验的情况下获得返回到 currentPage 索引的所需分页器行为?
【问题讨论】:
标签: angular pagination angular-material2