获取 ngFor 项目的索引并更新值

Get index of ngFor item and update value

我正在尝试更新 Angular 模板中输入字段的文本值。模板数据值在 NgFor 循环中生成,该循环从 Web 服务获取值。这是我的模板。

<ul *ngFor="let item of vals?.bu">
  <li>
    <table>
          <tr>
            <td><button type="button" class="btn btn-info">{{item?.id}}</button></td>
            <td><input type="text" [(ngModel)]="item.bcluster"></td>
            <td><input type="text" [(ngModel)]="item.bsector"></td>
            <td><button type="button" id={{item?.id}} (click)="update($event)">Update</button></td>
          </tr>
          <tr>
            <td></td>
            <td><input type="text" [(ngModel)]="item.bgroup"></td>
            <td><input type="text" [(ngModel)]="item.bunit"></td>
            <td><button type="button" id={{item?.id}} (click)="delete($event)">Delete</button></td>
          </tr>
      </table>

  </li>
</ul>

我现在需要从模板中获取字段的值,即 'bcluster, bsector, bgroup, bunit' 到我的 TS 文件中,以便调用更新 API 调用(通过更新按钮上的点击事件) ,但是当我尝试获取值时,我得到了未定义的值,因为我没有得到确切的行索引。我不知道该怎么做。

这是我的 TS 文件(只是想得到安慰出来的值)

  update(event) {
    console.log(this.bcluster);
  }

语法是

*ngFor="let item of vals?.bu; let i = index;"

您现在可以将 i 传递给您的函数。

更新 ul 以定义索引

<ul *ngFor="let item of vals?.bu; let i = index">

并使用 i 作为你的函数参数

您应该从模板中传递项目和索引,例如

<ul *ngFor="let item of vals?.bu; let i = index;">
  <li>
    <table>
          <tr>
            <td><button type="button" class="btn btn-info">{{item?.id}}</button></td>
            <td><input type="text" [(ngModel)]="item.bcluster"></td>
            <td><input type="text" [(ngModel)]="item.bsector"></td>
            <td><button type="button" id={{item?.id}} (click)="update(item,i)">Update</button></td>
          </tr>
      </table>

  </li>
</ul>

比在 ts

update(item,idx) {
    //here idx will give you the index
    console.log(item.bcluster);
  }