MatPaginator does not work properly with dynamically loaded data
MatPaginator should work the same even if the table/paginator are within *ngIf
MatPaginator does not work at all
https://stackblitz.com/edit/angular-8e1csg
The paginator should work within the ngIf
Angular 6.0.3, Material 6.2.1
If I replace the *ngIf="dataSource" with [style.display]="dataSource ? 'block' : 'none'", then the paginator works fine.
This is pretty much not a problem of the paginator. Put console.log(this.paginator) infront of this.dataSource.paginator = this.paginator; and see, that it's still undefined.
So you are essentially assigning undefined to this.dataSource.paginator - which obviously doesn't work.
You can try something like that to overcome your problem:
@ViewChild(MatPaginator)
set paginator(value: MatPaginator) {
this.dataSource.paginator = value;
}
@pfeigl is correct - the paginator value is undefined because you have an ngIf. Unfortunately it is part of the mechanics of Angular that ngOnInit will not catch view children that are contained within an ngIf.
For what it's worth, I found it easier to move the data table to it's own component with the loaded data as an @Input() - this meant that from the POV for the data table everything was available synchronously, so I didn't have to change the way the parent component worked.
@studds good suggestion, that is what I have done as well, thanks!
For me the problem was that I was setting the dataSource from service after setting the this.dataSource.paginator. I used the method suggested by @pfeigl and stored the value of paginator in another variable, and then set the value of this.dataSource.paginator after fetching data from service. Like,
actualPaginator: MatPaginator;
@ViewChild(MatPaginator)
set paginator(value: MatPaginator) {
this.actualPaginator = value;
}
The value is not retained in paginator property. Then after setting dataSource,
this.dataSource.paginator = this.actualPaginator;
This way, we can set the this.dataSource.paginator again, if we are performing a search api or something. Hope this helps someone.
This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.
Read more about our automatic conversation locking policy.
_This action has been performed automatically by a bot._
Most helpful comment
For what it's worth, I found it easier to move the data table to it's own component with the loaded data as an
@Input()- this meant that from the POV for the data table everything was available synchronously, so I didn't have to change the way the parent component worked.