【问题标题】:Range of mat-paginator sets back to its initial value when list is rendered渲染列表时,mat-paginator 的范围设置回其初始值
【发布时间】:2020-03-29 01:53:55
【问题描述】:

我正在使用 Angular Material 分页器在后端 API 的帮助下实现分页。当单击下一个按钮时,分页器的范围会更新,但一旦呈现列表,范围就会再次显示 1-10。这是我的代码:

getNext(event: PageEvent) {
        this.applicationService.getNextApplications(event).subscribe((applications: PaginationModel) => {
            this.dataSource.data = applications.data;
            this.dataSource.data = this.dataSource.data.sort((a, b) => a.appName.localeCompare(b.appName));
            setTimeout(() => {
                this.dataSource.paginator.length = applications.totalCount;
                this.limit = event.pageSize;
            });
            this.isDataReceivedByServer = true;
        });
    }

上述方法调用api并获取分页值

ngAfterViewInit() {
        this.dataSource.sort = this.sort;
        setTimeout(() => {
            this.dataSource.paginator = this.paginator;
        });
    }
<mat-paginator [length]="totalLength" [pageSize]="limit" [pageSizeOptions]="[10, 25,50, 100]"
    (page)="getNext($event)">
  </mat-paginator>

我不明白为什么分页不能正常工作并且值被设置为其初始值。

【问题讨论】:

  • 您能否提供最少的可复制代码,例如在 StackBlitz 中?据我所知,在使用正确的 Observable 初始化变量后,您需要在 dataSource 上使用 async 管道。如果没有可复制的代码,我就不能正式。

标签: html angular pagination


【解决方案1】:

dataSource 将分页器的 pageIndex 设置为 0。所以我必须在 setTimeOut 函数中获取当前页面并将其绑定到 dataSource.paginator 的 pageIndex 属性。 getNext(event: PageEvent) { this.userService.getNextUsers(event).subscribe(users => { this.dataSource.data = users.data; this.dataSource.data = this.dataSource.data.sort((a, b) =>a.firstName.localeCompare(b.firstName)); setTimeout(() => { this.dataSource.paginator.length = users.totalCount; this.dataSource.paginator.pageIndex = users.currentPage - 1; this.limit = event.pageSize; }); this.isDataReceivedByServer = true; }); }

【讨论】:

    【解决方案2】:

    您必须明确更新MatPaginator.pageIndex。不确定您的示例中的 this.dataSource 是由什么制成的。也许您可以使用this.dataSource.paginator.pageIndex,否则请尝试先使用@ViewChild 获取对MatPaginator 的引用。

    @ViewChild(MatPaginator, {static: false}) paginator: MatPaginator;
    
    getNext(event: PageEvent) {
        ...
        this.paginator.pageIndex += 1;
        ...        
    }
    

    【讨论】:

    • dataSource = new MatTableDataSource&lt;ApplicationModel&gt;(); dataSource 用于存储来自 API 的响应以显示在 mat 表中。我已经使用了@ViewChild 行。实际上,问题是范围在单击下一步按钮时会更新,但是一旦呈现列表,范围就会再次变为初始值。
    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 2011-04-25
    • 2019-07-08
    • 2021-09-24
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多