2 mat-paginator for the same data source

Issue

I have a mat-table that might show up to 100 entries per page. At first, I had one mat-paginator at the bottom that worked fine. Now I’m being asked to set a paginator at the top and another one at the bottom of the table, so the user won’t have to scroll all the way down to reach the paginator if they are looking for an entry that is at the top.

The thing is that both paginators must be linked to the same data source.
I´ve tried giving a different id for each one, using ViewChild to get them and assign them to the same data source, but it only works with one of them.

main.component.ts:

    flights: Flight[] =[];
    dataSource = new MatTableDataSource<Flight>(this.flights);
    @ViewChild('PAGINATOR') paginator: MatPaginator;
    @ViewChild('OTROPAGINATOR') paginatorOtro: MatPaginator;

main.component.html:

   <mat-paginator #PAGINATOR (page)="pageEvent = handlePage($event)" 
   [length]="length" [pageSizeOptions]="[25, 50, 100]" showFirstLastButtons> 
   </mat-paginator>

   <table mat-table ...> ... </table>

  <mat-paginator #OTROPAGINATOR (page)="pageEvent = handlePage($event)" 
  [length]="length" [pageSizeOptions]="[25, 50, 100]" showFirstLastButtons> 
  </mat-paginator>

Linking paginators to data source:

    this.dataSource = new MatTableDataSource<Flight>(this.flights);
    this.dataSource.paginator = this.paginator;
    this.dataSource.paginator = this.paginatorOtro;

Could someone guide me with this, please?

Solution

I couldn’t find a way to set up 2 paginators for the same data souce. The way I did it, is setting up a second paginator with a copy of the data source, then moving each paginator based on the changes of the other one.

Also, I couldn’t set the page index or items per page properties directly (the table was not refreshing), so all the movements are achieved with some logic and paginator methods like previousPage() or lastPage().

The only limitation is that the paginator at the bottom can’t change items per page, since there isn’t a method that lets me control that property.

You can see the result here. Thanks FabianKüng for the solution on using 2 data sources and syncing both paginators.

I hope this is useful for someone.

Answered By – Gustavo Alejandro

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.