我正在使用angular实现购物车。根据用户单击添加到购物车按钮的次数,我想将输入字段(即数量字段)的值设置为用户单击添加到购物车按钮的次数。
我正在为此使用反应形式。如何做到这一点? https://stackblitz.com/edit/angular-qarnso
我尝试通过[value] =“ item.quantity”设置值,但没有得到结果。
<form [formGroup]="cartForm">
<div formGroupName="quantity">
<table class="uk-table">
<caption></caption>
<tbody>
<th class="uk-margin-left uk-width-large@m">Total Items: {{ cartItems.length }}</th>
<tr>
<td>
<div *ngIf="cartItems?.length > 0">
<div class="uk-margin" uk-grid>
<div *ngFor="let item of cartItems" class="uk-card-media-bottom uk-cover-container">
<img [src]="item.productImageUrl" alt="{{ item.productName }}"
class="uk-margin-xlarge-left uk-margin-medium-top">
</div>
</div>
</div>
</td>
<td>
<div *ngFor="let item of cartItems">
<div class="uk-card-body">
<h3 class="uk-card-title">{{ item.productName }}</h3>
<p>{{ item.productDesc }}</p>
<p>Price: {{ item.productPrice}}</p>
<div class="uk-width-1-3@s">
Quantity: <input class="uk-input uk-margin-top" type="number"
name="quantity" formControlName="qty" [value]="item.productQty"/>
</div>
<div class="uk-margin">
<p class="uk-text-success">Available Stock Item: {{ item.productQty }}</p>
</div>
</div>
<p>Total: {{ cartForm.value | json }}</p>
</div>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>
</form>
initForm() {
this.cartForm = new FormGroup({
quantity: new FormGroup({ qty: new FormControl() })
});
addToCart(product: Product) {
const addedProducts = this._cartItem.find(el => el.id === product.id)
console.log('Added Products', addedProducts);
if(addedProducts) {
addedProducts.productQty++;
console.log('Quantity Products:', addedProducts.productQty);
}
else {
this._cartItem.push({
id: product.id,
productName: product.productName,
productDesc: product.productDesc,
productPrice: product.productPrice,
productQty: product.productQty,
productImageUrl: product.productImageUrl
});
}
/* console.log('Cart Item:', this._cartItem); */
setTimeout(()=> {
localStorage.setItem('cart', JSON.stringify(this._cartItem));
this.calculateProducts();
},1000);
}
反应形式输入字段的值应基于用户单击添加到购物车中的次数。
答案 0 :(得分:0)
要计算总数,请使用以下内容:
getTotal(): number {
let total = 0;
(this.cartForm.get('items') as FormArray).controls.forEach(
(fg: FormGroup) => {
total += fg.controls.qty.value;
}
);
return total;
}
在您的html中:
<p>Total: {{ getTotal() }}</p>
更新
要进行最大程度的验证,可以在 createItem 方法中添加此代码:
qty: [product.productQty, Validators.max(product.productQty)]
现在验证已经到位。如果输入更多,那么productQty的表格将无效。要验证这一点,请在html中添加以下内容:
Form Valid: {{ cartForm.valid }}
但是,这是一个全局错误。要获取每个字段的本地地址,请将此方法添加到 cart.component.ts :
getValidity(index: number): boolean {
return (<FormArray>this.cartForm.get('items')).controls[index].invalid;
}
此html在数量输入字段下:
<div *ngIf="getValidity(i)">Too many</div>
更新了Stackblitz。
第二次更新
要从FormArray删除项目,可以使用以下简短方法:
deleteItemFromTheCart(index: number): void {
console.log('delete item from the cart at: ', index);
(<FormArray>this.cartForm.get('items')).removeAt(index);
}
在html中添加以下行:
<button (click)="deleteItemFromTheCart(i)">Delete</button>
新的Stackblitz。