我的 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>
但是,当我尝试手动(使用 UI)更改页面大小(无需刷新页面)时,数据开始正确显示并且分页工作完美。
可能是什么原因? 为什么 mat-paginator 无法正确初始化?
您将
totalItems
设置为 API 返回的对象数组。相反,您的 totalItems
应该是该数组的长度,如下所示:
this.totalItems = response.paging.totalItems.length