8

I am using the MatTable component from Angular Material to make a dynamic data table.

I need to get the current position of a row. I can easily get the row on which the user clicked but I am unable to know its current position in the list (which depends on sort/filtering/pagination).

Any idea?

2
  • Do you use *ngFor to create rows dynamically? Commented May 2, 2018 at 20:42
  • @CommercialSuicide No I use mat-rows and mat-cells etc Commented May 2, 2018 at 20:47

4 Answers 4

25

in your mat-cell you can get index like *ngFor as below

<mat-cell *matCellDef="let element;let i = index;">
        {{ i }}
</mat-cell>

Update from Angular 5 use also index as i

<ng-container matColumnDef="rowIndex">
  <th mat-header-cell *matHeaderCellDef> Index </th>
  <td mat-cell *matCellDef="let element;index as i;"> {{ i }} </td>
</ng-container>
  • index: number: The index of the current item in the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.
Sign up to request clarification or add additional context in comments.

5 Comments

It's not related to row data its just the current row index in the HTML table
Yes, If you need the index to be related to row data you need to add it to your data, so it will not be changed on sorting or filter
what do you mean by id of the html row?
the index of the row will remain even if material angular changes the content ? that is why this angular ngfor work ?
Yes, its related to loop, not the data
2

I searched a lot, but for my case "indexOf" scenario doesn't work properly then I found this answer, and it does exactly what I need.

let i = index;
i + (paginator.pageIndex * paginator.pageSize);

Comments

1

Are you using angularjs or angular2? your title says angularjs but your tags and post say otherwise.

angular2

<div *ngFor="item of items; i = index">
  <span click(item, i)>
</div>

angularjs

<div ng-repeat="item of items">
  <span click(item, $index)>
</div>

edit: I saw your comments, does this answer help you out? Is there an index property with CDK data table or Material2 data table?

Comments

1

For Angular 10+

Try using index as i

Example:

 <ng-container matColumnDef="columnName">
     <th mat-header-cell *matHeaderCellDef>
     </th>
     <td mat-cell *matCellDef="let row; index as i">
        <button (click)="selectedItem(i)"> Button </button>
     </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.