我有一个项目,我正在从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>
类似这样的东西
如何将复选框值和输入字段值绑定在一起,以便更新值? 我有来自api的json格式的数据,例如
[{id:'1', price:'20',title:'bag'},{id:'2', price:'10',title:'shirt'}]
我只想通过在输入字段中输入价格以及选中复选框来更新价格。 如何绑定两个值?
我想要这样的东西,必须从视图中获取复选框和更改的输入值,而不是在按钮更新时我可以更新所选值。
我还希望,如果我选中所有复选框,则选中的复选框以及相应的输入字段值也应通过单击update all
按钮进行更新。
答案 0 :(得分:1)
要获得预期的结果,请使用以下使用ngModel的选项,单击并更改事件以更新产品的对象数组
<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>
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