[英]Angular is updating all fields simultaneously when it should just update one
[英]All of the text inputs are updating when I click on just one button
我有一个带有增量和减量按钮的组件。 我循环浏览产品,每个产品旁边都会显示按钮。 当我单击其中一个按钮时,所有文本输入都会更新,而不仅仅是我单击的那个。
组件 HTML:
<div *ngFor="let product of products">
<button (click)="minus()" type="button">
-
</button>
<input id="number" type="text" value="1" [(ngModel)]="count">
<button (click)="plus()" type="button">
+
</button>
</div>
组件 TYPESCRIPT:
count: number = 1;
plus(){
this.count++;
}
minus(){
if (this.count > 1) {
this.count--;
}
}
当我使用:
<div *ngFor="let product of products; let i = index">
<input id="number" type="number" value="1" [(ngModel)]="products[i].count">
</div>
我收到错误:类型'{ id:number; 上不存在属性'count'; 名称:字符串; 价格:数量; 描述:字符串; }'。
当我使用:
<input id="number" type="number" value="1" [(ngModel)]="product[i].count">
我得到错误:
元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引类型“{ id: number; 名称:字符串; 价格:数量; 描述:字符串; }'。 在类型“{ id: number; 名称:字符串; 价格:数量; 描述:字符串; }'。
products 数组定义如下:
export interface Product {
id: number;
name: string;
price: number;
description: string;
}
这是因为它们都引用了相同的变量,因为 ngModel 以及您迭代产品并使用单个输入引用的事实 - 所以当您单击按钮并更改计数时 - 它们都会更新,因为它们都在听同一个变量。
<input id="number" type="text" value="1" [(ngModel)]="count">
为了防止这种情况 - 您需要为每个应用不同的 ngModel 引用,并更改您的增量和减量 function 以仅应用于该项目。
<input id="number" type="text" value="1" (ngModel)]="products[index].count">
这里的问题是您为不同的数组元素定义了相同的变量。 解决方案是为每个数组元素分配一个计数值。 为此,您需要更新所有数组元素的计数值。
HTML
<div *ngFor="let product of products; let i=index">
{{product.name}}
<button (click)="minus(i)" type="button"> - </button>
<input id="number" type="text" [value]="product.count">
<button (click)="plus(i)" type="button"> + </button>
</div>
TYPESCRIPT
export class AppComponent implements OnInit {
products: any[] = [
{ name: 'product 1' },
{ name: 'product 2' },
{ name: 'product 3' },
{ name: 'product 4' }
];
count: number = 1;
ngOnInit() {
this.migrateAllProducts();
}
migrateAllProducts() {
this.products.forEach(p => {
p.count = this.count;
});
}
plus(index: number) {
this.products[index].count++;
}
minus(index: number) {
if (this.products[index].count > 1) {
this.products[index].count--;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.