[英]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.