0

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?

Brian
  • 4,958
  • 8
  • 40
  • 56

1 Answers1

0

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>
Evan Sexton
  • 21
  • 1
  • 3
  • This does not solve my problem since I don't have a defined number of tables, hence cannot declare `sort1`, `sort2`, ... – Brian Aug 09 '22 at 19:54
  • 1
    I may have made the example a little confusing, but even though I have 2 tables within each record, the total number of records I get back from the API is unknown. So ultimately the total number of tables was not predefined. In my example sort1 and sort2 actually represent a list of sorts for each instance of 'table1' and 'table2'. In your example are you wanting to just display a single mat-table within an ngFor? If so I can make an easier to follow example for your use case – Evan Sexton Aug 10 '22 at 20:12