Search code examples
angularangular-material-table

Angular material table to change data based on click of next results


i am using angular material table, and here pagination requirement is that, initial need to show only 5 records and when click of next button, need to show rest 5 records, when click of previous 5 results, it has to come back to 0to 4 index values.

Demo

TS:

pageChange() {
    this.dataElement.slice(0, 5);
  }

HTML:

<mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.position}} </mat-cell>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
<h2 class="pagination-style" (click)="pageChange()">Next 5 results</h2>

Solution

  • slice returns a piece of the array but it doesn't affect the original array. splice changes the original array by removing, replacing, or adding values and returns the affected values

    Hope this helps !

    https://stackblitz.com/edit/angular-5m6rnk-7nvbsm?file=src%2Fapp%2Ftable-flex-basic-example.html,src%2Fapp%2Ftable-flex-basic-example.ts,src%2Fapp%2Ftable-flex-basic-example.css