角度6:如何通过选中复选框来更新多个输入字段的值?

时间:2019-07-09 17:36:20

标签: javascript angular6

我有一个项目,我正在从API调用中获取数据。数据是从数据库中动态获取的,并显示在视图上。

现在,我在获取的每个值上都有一个复选框和一个输入字段, 我有一个按钮updateALL,我想要的是应该通过单击选中其复选框的updateAll按钮来更新我在输入字段中插入的值。

然后选中所有复选框,并更新输入字段的值。

类似这样的东西

<div *ngFor="let product of products">
<input type="submit" value="Update All"><br>
  <input type="checkbox" name="vehicle1" value="Bike">
  <input type="text">
  <input type="submit" value="update">
</div>

类似这样的东西

enter image description here

如何将复选框值和输入字段值绑定在一起,以便更新值? 我有来自api的json格式的数据,例如

[{id:'1', price:'20',title:'bag'},{id:'2', price:'10',title:'shirt'}]

我只想通过在输入字段中输入价格以及选中复选框来更新价格。 如何绑定两个值?

我想要这样的东西,必须从视图中获取复选框和更改的输入值,而不是在按钮更新时我可以更新所选值。

enter image description here

我还希望,如果我选中所有复选框,则选中的复选框以及相应的输入字段值也应通过单击update all按钮进行更新。

enter image description here

1 个答案:

答案 0 :(得分:1)

要获得预期的结果,请使用以下使用ngModel的选项,单击并更改事件以更新产品的对象数组

  1. 将ngModel添加到具有click事件的输入和复选框字段以更新价格

<input type="submit" value="Update All" (click)="updatePriceAll()">
<div *ngFor="let product of products;">
<br>
  <input type="checkbox" name="vehicle1" value="Bike" (change)= "updatePrice(product, vehicle[product.id])" [(ngModel)]="vehicle[product.id]">
  <input type="text" [(ngModel)]="newPrice[product.id]">
  <input type="submit" value="update" (click) ="updatePrice(product, true)">
</div>

  1. 在复选框上使用更改事件并标记以检查检查条件
  2. 在component.ts中,创建了updatePrice和updatePriceAll方法以进行检查,单击update,updateaLL按钮进行更新

newPrice= {}; vehicle = {}; products= [{id:'1', price:'20',title:'bag'},{id:'2', price:'10',title:'shirt'}]

updatePrice(val, flag){ if(flag){ this.products = this.products.map(v => { if(v.id === val.id){
v.price = this.newPrice[v.id]; } return v }) } console.log(this.newPrice[val.id]); }

updatePriceAll(){ this.products = this.products.map(v => { if(this.newPrice[v.id]){
v.price = this.newPrice[v.id]; } return v }) console.log(this.newPrice); }

工作代码示例-https://stackblitz.com/edit/angular-gtnkor?file=src/app/app.component.html