Angular Material 18 - Mat-paginator [长度] 问题

问题描述 投票:0回答:1

我的 mat-paginator 组件有问题。

displayedColumns: string[] = ['id', 'name'];
  dataSource = new MatTableDataSource<any>();
  totalItems = 0;

  @ViewChild(MatPaginator) paginator!: MatPaginator;

  constructor(private colorService: ColorsHttpService, private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    this.dataSource.paginator = this.paginator;
    
    this.loadData(1, 10);
  }

  loadData(pageNumber: number, pageSize: number) {
    this.colorService.getColors(pageNumber, pageSize).subscribe(response => {
      this.dataSource.data = response.items;
      this.totalItems = response.paging.totalItems;
      this.paginator.pageIndex = response.paging.pageNumber - 1;
      this.paginator.length = response.paging.totalRows;

      this.cdr.detectChanges();
    });
  }

  onPageChange(event: any) {
    this.loadData(event.pageIndex + 1, event.pageSize);
  }
<mat-paginator [length]="totalItems"
                   [pageSize]="10"
                   [pageSizeOptions]="[5, 10, 20]"
                   (page)="onPageChange($event)">
    </mat-paginator>

我在组件中设置了项目数,但在视图中我看到项目数为 0。 enter image description here

但是,当我尝试手动(使用 UI)更改页面大小(无需刷新页面)时,数据开始正确显示并且分页工作完美。 enter image description here

可能是什么原因? 为什么 mat-paginator 无法正确初始化?

angular angular-material mat-pagination
1个回答
0
投票

您将

totalItems
设置为 API 返回的对象数组。相反,您的
totalItems
应该是该数组的长度,如下所示:

this.totalItems = response.paging.totalItems.length
© www.soinside.com 2019 - 2024. All rights reserved.