Search code examples
angularangular-cdk

Row index is not available in Angular CDK table


I have a simple table like this

<table cdk-table [dataSource]="doors" [multiTemplateDataRows]="true" class="table table-hover">
  <ng-container cdkColumnDef="width">
    <th cdk-header-cell *cdkHeaderCellDef>Width</th>
    <td cdk-cell *cdkCellDef="let row; let idx = index;">
      Index: [{{idx}}]
      <span *ngIf="idx === undefined">undefined</span>
      <span *ngIf="idx === null">null</span>
    </td>
  </ng-container>

  <tr cdk-header-row *cdkHeaderRowDef="['width']"></tr>
  <tr cdk-row *cdkRowDef="let row; let i = index; columns: ['width']"></tr>
</table>

I need to access row index but it is undefined. What am I doing wrong?

Stackblitz: https://stackblitz.com/edit/angular-3cknv1


Solution

  • You should use let idx = dataIndex;

    Since you are using [multiTemplateDataRows]=true.

    From the source:

    /**
     * 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`.
     */
    

    Look here for more info