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
Although selected answer works and solves the problem it is still a workaround. This is proper and more elegant way to deal with the problem.
Try adding AfterViewInit
interface to your class, then put this.dataSource.paginator = this.paginator
inside ngAfterViewInit()
method
ngAfterViewInit() {
this.dataSource.paginator = this.paginator
}
then you would not have to call workaround setTimeout
.
I had a similar issue to this, with mat-paginator
inside a container with a ngIf
.
The only thing that worked for me was the comment:
Thank you - this was the solution for me. I opted to use [hidden] instead of ngIf so that the paginator would render even if there wasn't any data, but wouldn't show up to the user – TabsNotSpaces
To clarify, what I did was create a div
, outside the container, with [hidden]=<negation_of_the_same_condition_as_the_ngIf>
.
Make sure that you have imported the MatPaginatorModule
in the app.module.ts
Using async-await worked for me inside ngOnInit(), the paginator and sort has to wait!
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
.
.
.
ngOnInit() {
this.isLoading = true;
this._statsService.getAllCampgrounds().subscribe(
async (response) => {
this.allCampgrounds = response.allCampgrounds;
this.dataSource = await new MatTableDataSource(this.allCampgrounds);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.isLoading = false;
},
(error) => {
this.isLoading = false;
console.log(error);
}
);
}
A solution without using setTimeout
is to use set
:
@ViewChild(MatPaginator) paginator: MatPaginator;
set matPaginator(mp: MatPaginator) {
this.paginator = mp;
this.dataSource.paginator = this.paginator;
}
In my case, the <mat-paginator>
element was inside a container that had an *ngIf
on it, which did not render until the data loaded asynchronously. This causes this.paginator
to be undefined
even in ngAfterViewInit
. This causes it to silently fail as MatTableDataSource
has no problem with you setting paginator
to undefined
.
The solution was to move the <mat-paginator>
outside of the *ngIf
'd container
Hopefully, this helps someone who is in the same situation as me.