Brian Stanley
Brian Stanley

Reputation: 2196

Mat-Table with paginator not passing correct index for edit/delete

I am using a mat-table to display some information. I have a column for edit using mat-icon that has a click listener on it. The function that I am firing from that icon takes an index number to then pull from the array that I am populating my dataTableSource with. However the index number being passed is off because of the use of the material paginator. It is passing the index of the rows being shown on the current page length and not the index of the item in the overall array of data supplied to the dataTableSource.

component.html:

<mat-table #table [dataSource]="productData">

**Other Columns**

  <ng-container matColumnDef="editItem">
    <mat-header-cell *matHeaderCellDef> Edit Item </mat-header-cell>
    <mat-cell *matCellDef="let productInfo"> <mat-icon matTooltip="Edit 
    List" class="pointer">edit</mat-icon> </mat-cell>
  </ng-container>

</mat-table>

component.ts:

editProductList(index) {
this.productListService.changeProductId(this.productList.data[index].id);
this.router.navigate(['ProductList/Edit']);
}

Do I have to sacrifice the mat-paginator to be able to get the functionality I am looking for? If not, how can I capture the correct index of the items in the mat-table?

Help and tips are much appreciated.

Upvotes: 5

Views: 1798

Answers (1)

bugs
bugs

Reputation: 15323

The paginator element has a page event you can listen to, to keep track of what page is currently being displayed, and how many items per page.

You can store those two values in your component (i.e. currentPage and itemsPerPage) and then offset your index by the required amount.

This means you have to modify your function like this:

editProductList(index) {
  const realIndex = index + this.currentPage * this.itemsPerPage;
  this.productListService.changeProductId(this.productList.data[realIndex ].id);
  this.router.navigate(['ProductList/Edit']);
}

Upvotes: 4

Related Questions