0

Currently I have an index column using this code:

<ng-container matColumnDef="id">
  <mat-header-cell *matHeaderCellDef mat-sort-header>Id</mat-header-cell>
  <mat-cell *matCellDef="let row; let i = index;">{{i}}</mat-cell>
</ng-container>

The problem with this code is that the numbers don't move when I sort by other columns. ie. It starts with all rows having descending indices but then if I sort by another row the index column stays the same while all other columns adjust.

2 Answers 2

2

You should add a property (ex: position) to your objects in the array the table represents. That will also allow you to add pagination and correctly display values in that column with incrementing numbers.

See this example from the Material Docs.

Sign up to request clarification or add additional context in comments.

3 Comments

index is being generated by the mat-cell element and whenever you are rearranging/sorting the table. it regenerates them. As explained by Nick, add index/position in the JSON to keep it consistent with your data.
What I want is a bit different. Loads all elements automatically sorted by a column (already done), based on this order each row is designated an index with 1 at the top, then if the rows are reordered the index remains with the original row. By hardcoding position for each row, the index order at the beginning will not be ascending from 1 downwards after the sort by column.
If I'm understanding correctly, you can sort your array on the property (column) you want to use for the initial sort order and assign the position (index) at that point. Then pass the array to the mat-table's dataSource. Does that make sense?
0
<ng-container matColumnDef="Index">
   <th mat-header-cell *matHeaderCellDef> # </th>
   <td mat-cell *matCellDef="let element; index as i;">
      {{_paginator.pageSize * _paginator.pageIndex + i + 1}}    
   </td>
</ng-container>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.