You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular子组件中获取并使用*ngFor循环的当前索引?

解决方法

要让子组件拿到*ngFor的循环索引,得通过**输入属性(@Input)**把索引传递给子组件,具体步骤如下:

1. 修改父组件模板,传递索引

在<app-doc-item>标签里新增一个输入绑定,把循环的i传进去:

<app-doc-item
    *ngFor="let docFeatureEl of docFeatures; let i = index"
    [documentFeature]="docFeatureEl"
    [itemIndex]="i" <!-- 新增这一行 -->
></app-doc-item>

2. 子组件中定义输入属性接收索引

在子组件的.ts文件里,导入Input并定义接收索引的属性:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-doc-item',
  templateUrl: './doc-item.component.html',
  styleUrls: ['./doc-item.component.css']
})
export class DocItemComponent {
  @Input() documentFeature: any; // 原有的输入属性
  @Input() itemIndex: number; // 新增接收索引的属性

  onSelected(index: number) {
    // 这里可以用index做特定实例的操作
    console.log('当前选中的索引:', index);
  }
}

3. 子组件模板中使用索引

现在就能直接在模板里打印索引,并且在点击事件中传递它:

<a href="#" class="list-item" (click)="onSelected(itemIndex)">
  <div class="pull-left">
    <h4 class="list-group-item-heading">{{ docFeature?.string }}</h4>
    <p>当前索引:{{ itemIndex }}</p> <!-- 打印索引 -->
  </div>
</a>

这样就不会再出现“property 'i' does not exist on type”的错误了,因为子组件已经通过输入属性拿到了父组件传递过来的索引值。

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:40:35