【问题标题】:Angular Edit all values on a table角度编辑表格上的所有值
【发布时间】:2020-03-25 13:49:51
【问题描述】:

我有一个要在表格上显示的数组,但我需要编辑该表格一列中的所有值。我的代码是这样的:

<tr *ngFor="let line of invoice.lines; let index = index">
    <td>
        {{line.quantity}}
    </td>
    <td style="width: 35%">
        {{line.productName}}
    </td>
    <td>
        <input type="number" class="form-control" name="order_price"
        id="field_order_price" [(ngModel)]="line.price"/>
    </td>
...
</tr>

问题是input 在所有行中都具有相同的值(这是数组中的最后一个)。我尝试在input 旁边打印line.price 的值,以确保我得到了正确的值,这就是我得到的:

我错过了什么?

更新 1:由建议更改没有工作:(

<input type="number" class="form-control" name="order_price" (click)="onOrderPriceChange(index)" id="field_order_price1_{{index}}" [(ngModel)]="invoice.lines[index].price"/>

角度:

trackByIndex(index: number, line: IInvoiceLine): any {
    return line.id;
  }

【问题讨论】:

  • 在*ngFor 指令中遇到[(ngModel)] 的问题似乎很常见。我自己还没有遇到过这个,但也许看看这个:stackoverflow.com/a/40315703/12431728
  • 我添加了trackBy,但并没有改变问题

标签: angular


【解决方案1】:

您需要为每个输入提供一个唯一的 ID。您也可以使用下面的代码来解决您的问题。

<tr *ngFor="let line of invoice.lines; let index = index">
  <td>
      {{line.quantity}}
  </td>
  <td style="width: 35%">
      {{line.productName}}
  </td>
  <td>
      <input type="number" class="form-control" [id]="'field_order_price' + index" [(ngModel)]="line[index]" />
  </td>
</tr>

希望这会有所帮助! 谢谢。

【讨论】:

  • 在回答之前对“id”的相同评论
  • noup,您的评论不适用于此答案。这个答案也是正确的。
【解决方案2】:

每个输入都应该有一个唯一的 ID 属性。如果您有任何疑问,请告诉我。

<tr *ngFor="let line of invoice.lines; let index = index">
  <td>
    {{line.quantity}}
  </td>
  <td style="width: 35%">
    {{line.productName}}
  </td>
  <td>
    <input type="number" class="form-control" name="{{'order_price_' + index}}" id="{{'field_order_price_' + index}}" [(ngModel)]="invoice.lines[index].price" />
  </td>
</tr>

希望这会有所帮助:)

【讨论】:

  • 几乎在那里,我仍然看到 '12' 作为值,但是在检查时我可以看到正确的值是 'ng-reflect-model="16.95"' 为什么会这样吗?
  • 只是想知道您是否更新了代码中显示的Id 和[(ngModel)]?显然,多个属性具有相同的 id 可能会导致这种情况
  • @Alejandro 我已经更新了答案,结果name 也需要是唯一的。试一试
  • 谢谢。这样做了,id 和 name 都必须是唯一的
  • @Ayyub,不需要唯一的“id”,真的不需要使用“id”。显然,关键是给 [(ngModel)] 提供不同的变量
猜你喜欢
  • 2018-03-13
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-20
  • 2021-08-17
  • 1970-01-01
  • 2016-10-18
相关资源
最近更新 更多