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

牧云@^-^@ 提交于 2019-12-12 16:45:32

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/53530994/in-angular-how-do-i-get-the-row-index-on-a-mat-table-with-expandable-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!