Search code examples
angularindexingrowmat-table

Angular table index is undefined with multiTemplateDataRows directive


I'm having trouble getting my table indexes to show up. Here's an example table:

<mat-table [dataSource]="dataSource" multiTemplateDataRows>

    <!--Column definitions-->        
    <ng-container matColumnDef="{{columnProp.name}}" *ngFor="let columnProp of columnProps; let i = index;">
        <mat-header-cell *matHeaderCellDef mat-sort-header>
            {{columnProp.name}} {{i}}
        </mat-header-cell>

        <mat-cell *matCellDef="let element; let j = index;">
            <div>{{element[columnProp.name}} {{j}}</div>
        </mat-cell>
    </ng-container>

    <!--Row definitions-->
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

    <!-- Row content-->
    <mat-row
        *matRowDef="let row; columns: displayedColumns; let k = index;"
        matRipple
        (click)="this.expandRow(row, k)">
    </mat-row>

    <!--Expanded row content-->
    <mat-row
        *matRowDef="let row; columns: ['expandedContent'];"
        [@detailExpand]="row == expandedElement ? 'expanded' : 'collapsed'">
    </mat-row>
</mat-table>

Column index i and j show up as expected, but when I click on my row, the index k shows up as undefined. What am I doing wrong here?


Solution

  • multiTemplateDataRows have a different variable to hold the row's index called dataIndex. Access the row's index using let k = dataIndex.

    <!-- Row content-->
    <mat-row
        *matRowDef="let row; columns: displayedColumns; let k = dataIndex;"
        matRipple
        (click)="this.expandRow(row, k)">
    </mat-row>
    

    Relevant github issue