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
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With