【问题标题】:Get index of ngFor item and update value获取 ngFor 项目的索引并更新值
【发布时间】:2018-06-11 06:54:18
【问题描述】:

我正在尝试更新 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);
  }

【问题讨论】:

  • 你传递 $event 而不是传递“item”,并且在你的 update(item) { console.log(item); }

标签: angular ngfor


【解决方案1】:

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

<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);
  }

【讨论】:

    【解决方案2】:

    更新 ul 以定义索引

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

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

    【讨论】:

      【解决方案3】:

      语法是

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

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

      【讨论】:

        猜你喜欢
        • 2020-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        相关资源
        最近更新 更多