21

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?

TabsNotSpaces
  • 1,224
  • 10
  • 22

3 Answers3

54

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

TabsNotSpaces
  • 1,224
  • 10
  • 22
0
[normal Table] 
 <mat-cell *matCellDef="let i = index;"> {{i + 1}} </mat-cell>
[multiTemplateDataRows Table] 
 <mat-cell *matCellDef="let i = dataIndex;"> {{i + 1}} </mat-cell>
user3205930
  • 51
  • 1
  • 2
  • 2
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney May 09 '22 at 00:50
0

Context provided to the row cells when multiTemplateDataRows is true. This context is the same as CdkCellOutletRowContext except that the single index value is replaced by dataIndex and renderIndex.

Ref to documentation: https://material.angular.io/cdk/table/api#CdkCellOutletMultiRowContext