Angular Material Paginator

Let's assume you've loaded the response data (Array) in requests .

You can probably create a method that returns a set of data from the requests property using the splice method.

Therefore, on the API subscribe results, it can be handled like this for the first time load:

this.request_service.get_requests()
  .subscribe((res) => {
    this.pageLength = res['requests'].length;
    this.splicedData = res['requests'].slice(((0 + 1) - 1) * this.pageSize).slice(0, this.pageSize);
  });

where pageSize, has been defined in earlier on to a default value.

Then, anytime the user changes the mat-paginator component in the template, the pageChangeEvent is run. Template looks like this:

  <mat-paginator (page)="pageChangeEvent($event)" [length]="pageLength" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions">
  </mat-paginator>

Then its corresponding component method is this.

 pageChangeEvent(event) {
    const offset = ((event.pageIndex + 1) - 1) * event.pageSize;
    this.splicedData = this.requests.slice(offset).slice(0, event.pageSize);
  }

Finally, your *ngFor can use the splicedData array to populate itself.

<mat-card *ngFor="let request of splicedData">
    <mat-card-title> {{ request.title }}</mat-card-title>
</mat-card>

You could use the mat-table, it integrates very well with the mat-paginator. Hiding the header and changing the style to make it look the way you want.

The component :

displayedColumns: string[] = ['requests'];
dataSource: MatTableDataSource<{request: number}>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;

constructor() {
 this.dataSource = new MatTableDataSource(values);
}

ngOnInit() {
 this.dataSource.paginator = this.paginator;
 this.dataSource.sort = this.sort;
}

The template :

<table mat-table [dataSource]="dataSource" matSort>

 <!-- Requests Column -->
   <ng-container matColumnDef="requests">
     <th mat-header-cell *matHeaderCellDef mat-sort-header/>
     <td mat-cell *matCellDef="let row"> {{row.request.title}} </td>
   </ng-container>

   <tr mat-header-row *matHeaderRowDef="displayedColumns"/>
   <tr mat-row *matRowDef="let row; columns: displayedColumns;">
   </tr>
</table>

<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"/>

Here is a running example.

Tags:

Angular