首页 > 解决方案 > 行索引在 Angular CDK 表中不可用

问题描述

我有一个像这样的简单表

<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>

我需要访问行索引,但它是未定义的。我究竟做错了什么?

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

标签: angularangular-cdk

解决方案


你应该使用let idx = dataIndex;

由于您使用的是[multiTemplateDataRows]=true.

从来源:

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

在这里查看更多信息


推荐阅读