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

Woody
  • 1,677
  • 7
  • 26
  • 32
  • If you pass element in function so you will get current row object. – Paresh Gami Nov 29 '18 at 02:45
  • 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. – Woody Nov 29 '18 at 03:13

1 Answers1

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

KShewengger
  • 7,853
  • 3
  • 24
  • 36