I have 2 components. Both have mat-table and paginators and pagination is working for one component and not working for the other component though the code is similar. Below
This took me hours to finally track down and understand why my table wasn't working. Placing some console.logs() helped me figure out the order of events and why it didn't work consistently. My scenario was similar to the original issue above with a dynamic data source, but slightly different. For me, when I would first refresh my angular app, the paginator state would be set and then the data for my table would be set. When these events would happen in the this order the paginator worked just as expected.
Because I was using ReplaySubjects for getting the data for my tables, my paginator state would be set in ngAfterViewInit and then the table data would come in from my subscription (it depends on user ID so I don't have an initial value and that is why I didn't use BehaviorSubjects). My problem was that, when I would navigate to another component in my app, and return to my dynamic table data source, the table data would be set before the paginator state. This would make the paginator show page x, but the displayed data would always be the first page of data.
To fix this annoying issue I:
setTableData() {
// set table data
this.tableData.data = this.images.filter(img => this.filterData(img));
// some other code below
....
}
// initialize our data source for our table and set flags for state
tableData = new MatTableDataSource(this.images);
loading = true;
setPageState = false;
ngAfterViewInit() {
// add pagination state to our table
setTimeout(() => {
console.log('Set paginator state');
this.setPageState = true;
this.paginator.pageIndex = this.state.pageIndex;
// check if we are not loading data, meaning the table came in first so
// we need to set the data here
if (!this.loading) {
this.setTableData();
}
}, 0);
}
ngOnInit() {
console.log('ngOnInit');
this.tableData.sort = this.sort;
this.tableData.paginator = this.paginator;
// listen for data
this.dbService.images.subscribe(images => {
console.log('Data subscription');
// save images
this.images = images;
// only set table data if paginator state has been set, otherwise it doesnt work
if (this.setPageState) {
this.setTableData();
}
// hide spinner and update that we have data
this.loading = false;
});
// other code
.....
}
And with that, my pagination was finally working consistently for when I first login to the app and when I navigate to other pages and go back to my dynamic table.