在Angular中,使用MatPaginator(分页器)时,如果在同一个组件中有多个表格,如何实现每个表格都有自己的分页器。
一种解决方案是使用@ViewChild和@ViewChildren实现在同一个组件中多个表格关联不同的分页器。
在组件HTML文件中定义多个表格:
在组件TS文件中定义分页器和视图查询:
@ViewChild(MatPaginator, {static: true}) paginator1: MatPaginator; @ViewChild('table1') table1: ElementRef;
@ViewChild(MatPaginator, {static: true}) paginator2: MatPaginator; @ViewChild('table2') table2: ElementRef;
在ngAfterViewInit钩子中为每个表格分配分页器:
ngAfterViewInit() { this.dataSource1.paginator = this.paginator1; this.dataSource2.paginator = this.paginator2; }
最后,在HTML文件中为每个表格绑定分页器: