4
votes

We know it is easy to do sorting and pagination in angular(only consider sorting in client end). refer to : https://stackblitz.com/angular/dnblbyvggqyj?file=src%2Fapp%2Ftable-sorting-example.ts. But how to integrate sorting and pagination for several seperate tables(same data structure for these tables).

For my understanding, in order to do this, we need serveral viewChild(the number of viewchild equals to the number of table). Also we need to initialize serveral MatTableDataSource objects. We can put it in a hashmap Like:

{table1Tittle: new MatTableDataSource<Object>(), table2Tittle: new MatTableDataSource<Object>(), ...., };

But the thing is we don't know the number of table before we get the data. How should we decorate the viewchild and let the number of viewchild to be same as the number of table.

1
There is a one key thing: we don't know how many table need to be generated before fetching the data. So we don't know how many ViewChild and MatTableDataSourceHongli Bu
can anyone help?Hongli Bu
you have multiple tables in single component and you want to show each of table with pagination right?Raj
@Raj yes! You are correct.Hongli Bu
do you have any idea how many tables will be in the same component?Raj

1 Answers

1
votes
{'k1' : [{'id' : '1'}, {'id': '2'} ], 'k2': [{}]} 

convert the object above to array and assign to tables and loop tables like below, Ignore if it is already an array.

you can do something like this in component1

     <div *ngFor="let t of tables">
     // app-table is the selector of component2
       <app-table [tablename]="t.k1" [tablesource]="t1.tableArray" > </app-table>        
       </div>

in component2.ts write something like this

import {MatPaginator} from '@angular/material/paginator';

copy below line below to your class constructor

@ViewChild(MatPaginator) paginator: MatPaginator;
 @Input() tablename: string;
 @Input() tablesource: any;

copy below line in your function

this.dataSource = new MatTableDataSource(this.tablesource);
this.dataSource.paginator = this.paginator;

create component2.html and write code like below

<table mat-table [dataSource] = "dataSource" class = "mat-elevation-z8" > 
        <ng-container matColumnDef = "id">
           <th mat-header-cell *matHeaderCellDef> id</th>
           <td mat-cell *matCellDef = "let element"> {{element.id}} </td>
        </ng-container>
         <ng-container matColumnDef = "id2">
           <th mat-header-cell *matHeaderCellDef> id2</th>
           <td mat-cell *matCellDef = "let element"> {{element.id2}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef = "displayedColumns"></tr>
        <tr mat-row *matRowDef = "let row; columns: displayedColumns;"></tr>
     </table>
     <mat-paginator [pageSizeOptions]="[20, 30, 50]" showFirstLastButtons></mat-paginator>