V
V
Vadimqa2020-05-04 10:07:40
Angular
Vadimqa, 2020-05-04 10:07:40

Angular MatPaginator - two tables in one component, paginators conflict?

If I add a second MatTable to the page, their paginators start to conflict

export class StatsComponent implements OnInit {

  dataSource_us: MatTableDataSource<any>;
  @ViewChild(MatPaginator, {static: true}) paginator_us: MatPaginator;

  dataSource_tr: MatTableDataSource<any>;
  @ViewChild(MatPaginator, {static: true}) paginator_tr: MatPaginator;

getStats() {

    this.statsService.getStats().subscribe((data: any) => {

// Здесь формируется первая таблица

this.dataSource_us = new MatTableDataSource(ustable);
this.dataSource_us.paginator = this.paginator_us;

// Здесь формируется вторая таблица

// И отсюда начинаются проблемы - в обоих таблицах спутывается пагинация
this.dataSource_tr = new MatTableDataSource(trtable);
this.dataSource_tr.paginator = this.paginator_tr;


I think you need to somehow bind the mat-paginator to the table, now everything looks like this in the template:
</table><mat-paginator [pageSizeOptions]="[2, 5, 30]" showFirstLastButtons></mat-paginator>
</table><mat-paginator [pageSizeOptions]="[10, 20, 30]" showFirstLastButtons></mat-paginator>


UPD:
The solution turned out to be simple: https://stackoverflow.com/questions/50428605/multi...
But one more problem got out:
My tables are formed either from localstorage or from a server call, conditionally allowed once a minute.
So. when the data comes from the server, everything is fine, but when it comes from localstorage, the paginator does not have time to accept the value (in my amateurish opinion, in the console matpaginator = undefined). I duplicated this.dataSource_us.paginator = this.paginator.toArray()[0]; and others in ngAfterViewInit
Visually, everything worked well, but now when accessing the server (allowed no more than once per minute), the console gives an error: undefined is not an object (evaluating 'this.dataSource_us.paginator = this.paginator.toArray()[0]') in ngAfterViewInit. It is clear that no one, including me, understands anything, but if suddenly someone understands what it is about, then I will be glad for any hints.
Some kind of crutch would come up with the condition that if the paginator worked in the function (in the subscribe subscription), then do nothing in ngAfterViewInit, but I can’t figure it out myself.

UPD:
Despite the advice to move the table into a separate component, I decided to cheat like this:
In the subscription, after the formation of the tables, I set a beacon that will send to ngAfterViewInit that the paginator did not have time to work

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question