Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 206
Woody Avatar asked Nov 29 '18 02:11

Woody


People also ask

How do you expand a row in a table in angular?

For keeping the table row expanded until you click on the row to collapse, you just need boolean flag on each element array. I would suggest to create property under your array as false and set it to toggle on click of row.

What is MatRowDef?

MatRowDef extends CdkRowDefData row definition for the mat-table. Captures the data row's template and other properties such as the columns to display and a when predicate that describes when this row should be used. Selector: [matRowDef]


1 Answers

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

like image 106
KShewengger Avatar answered Sep 30 '22 05:09

KShewengger