Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
TabsNotSpaces Avatar asked Nov 28 '18 16:11

TabsNotSpaces


People also ask

What is * MatHeaderCellDef?

MatHeaderCellDef extends CdkHeaderCellDefHeader cell definition for the mat-table. Captures the template of a column's header cell and as well as cell-specific properties.

What is mat-table?

The mat-table provides a Material Design styled data-table that can be used to display rows of data. This table builds on the foundation of the CDK data-table and uses a similar interface for its data input and template, except that its element and attribute selectors will be prefixed with mat- instead of cdk- .


1 Answers

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

like image 53
TabsNotSpaces Avatar answered Oct 02 '22 15:10

TabsNotSpaces