行索引在 Angular CDK table 中不可用

Row index is not available in Angular CDK table

我有一个简单的table像这样

<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

你应该使用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`.
 */

查看here了解更多信息

一样的问题

你应该像这样使用 dataIndex:

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