How to add paginator and sorting to unknown number of angular material tables?

257 views Asked by At

I have no problem in adding sorting and pagination to predefined tables like this:

@ViewChild('myTableSort') myTableSort:MatSort;
@ViewChild('myTablePaginator') myTablePaginator:MatPaginator;

then after getting table data:

this.tableData = new MatTableDataSource(data);
this.tableData.sort = this.myTableSort;
this.tableData.paginator = this.myTablePaginator;

This works fine but when I have an unknown number of tables, I need to programmatically add a paginator and sort to each table.

Can I somehow declare a new paginator myTablePaginator2 after getting table data?

How can I add a paginator and sort dynamically after creating tables?

1

There are 1 answers

2
Evan Sexton On

I had a similar situation where I needed to loop through records from an API response then create 2 tables with sorting for each record. I solved this with a QueryList

@ViewChildren('sort1') sort1: QueryList<MatSort>;
@ViewChildren('sort2') sort2: QueryList<MatSort>;
 
generateTables(): void {
  this.records?.forEach((record, i) => {
    record.tables = {
      table1: new MatTableDataSource(),
      table2: new MatTableDataSource(),
    };

    record.tables.table1.data = // API call to get table data
    record.tables.table2.data = // API call to get table data

    record.tables.table1.sort = this.sort1.get(i);
    record.tables.table2.sort = this.sort2.get(i);
  });
}

HTML

<div *ngFor="let record of records; let i = index">
  <table mat-table [dataSource]="record.tables.table1" matSort 
   #sort1="matSort">
  </table>

  <table mat-table [dataSource]="record.tables.table2" matSort 
    #sort2="matSort">
  </table>
</div>