In Angular, how do I get the row index on a Mat-Table with expandable content?
Asked Answered
I

1

7

I have a page that uses a mat-table with expandable content. I need to be able to have a click event that records the row number of the table that I am clicking on.

Now, if I have a table without the expandable content I can successfully use the following in the html file:

<tr mat-row *matRowDef="let row; columns: displayedColumns; let i = index"
    (click)="logIndex(i)">

and the following in the component file:

 logIndex(i)
  {
    console.log(i);
  }

but this doesn't work with expandable content. Here is a html file I am working with: Stackblitz HTML

which contains

<tr mat-row *matRowDef="let element; columns: columnsToDisplay;let i = index;"
      class="example-element-row"
      [class.example-expanded-row]="expandedElement === element"
      (click)="expandedElement = element"
      (click)="logIndex(i)">
  </tr>

and returns "undefined".

This is a simple example. In my actual page I am using a MatTableDataSource as the datasource for the mat-table. I am aware that I could use dataSource.filteredData.indexOf(element) in this situation to get the row number but the mat-table also uses a mat-sort and sorting the table will still return the original row number, not the index of the row after sorting. Can I do this? Thanks

Iveyivie answered 29/11, 2018 at 2:33 Comment(2)
If you pass element in function so you will get current row object.Vaios
Hi Paresh. Were you talking about the position property? If so, sorry that was misleading. I've removed it and updated the link. If not, can you show me what you mean? I don't understand how passing the element would get me the row number.Iveyivie
A
25

Instead of using let i = index; Use let i = dataIndex

<tr mat-row 
    *matRowDef="let element; columns: columnsToDisplay; let i = dataIndex;"
  class="example-element-row"
  [class.example-expanded-row]="expandedElement === element"
  (click)="expandedElement = element"
  (click)="logIndex(i)">

Referenced answer from a Github Material2 Issue Thread

Aronow answered 29/11, 2018 at 3:15 Comment(2)
Thank-you. I've been stuck on this for way too long.Iveyivie
This works - [ #49648770 ]Evania

© 2022 - 2024 — McMap. All rights reserved.