下面是我的FormArray,我想根据另一个输入的值更改来更新一个输入。每当用户更改产品时,服务都将获取price和taxPercent,这需要针对表单数组中的该索引进行修补,当添加数量时,我想对totalAmount进行修补。通过订阅相应的valueChanges并为相应的字段设置路径,这在表单控件元素中很容易。如何在FormArray中做同样的事情?
<div formArrayName="products" *ngFor="let product of productsArray.controls; let i=index">
<div [formGroupName]="i">
<div class="form-row">
<div class="form-group col-md-4">
<label for="product">Product</label>
<select formControlName="pdt" class="form-control" >
<option [value]="pdt.productPriceId" *ngFor="let pdt of productPrice">{{pdt.productName}} - {{pdt.size}}</option>
</select>
</div>
<div class="form-group col-md-1">
<label for="price">Price</label>
<input type="text" class="form-control" formControlName="price" id="price">
</div>
<div class="form-group col-md-1">
<label for="taxPercent">Tax %</label>
<input type="text" class="form-control" formControlName="taxPercent" id="taxPercent">
</div>
<div class="form-group col-md-1">
<label for="quantity">Qty</label>
<input type="text" class="form-control" formControlName="quantity" id="quantity">
</div>
<div class="form-group col-md-1">
<label for="totalAmount">Amt</label>
<input type="text" class="form-control" formControlName="totalAmount" id="totalAmount">
</div>
<div class="form-group col-md-1">
<span>
<button class="btn btn-primary" (click)=addProduct()>Add</button>
</span>
</div>
<div class="form-group col-md-1">
<span>
<button class="btn btn-primary" (click)=removeProduct(i)>Remove</button>
</span>
</div>
</div>
</div>
</div>
FormControl的“我的值更改订阅”如下所示。但是我不确定如何对FormArray做同样的事情
this.billingForm.get('products[0].pdt').valueChanges.subscribe(
(value) => {
console.log(value);
let taxPercentVal: Number = 0;
let priceVal: Number = 0;
this.productPrice.forEach(function (val) {
if(value == val.productPriceId)
{
taxPercentVal = val.taxPercent;
priceVal = val.price;
}
});
this.billingForm.patchValue({
products: {
taxPercent: taxPercentVal,
price: priceVal,
quantity: '',
totalAmount: ''
}
})
}
);
this.billingForm.get('products.quantity').valueChanges.subscribe((value) => {
console.log(value);
let taxPer = this.billingForm.value.products.taxPercent;
console.log(taxPer);
let pr = this.billingForm.value.products.price;
console.log(pr);
let qty = value;
console.log(qty);
let totAmt = (pr * qty) + ((pr * qty) / taxPer);
console.log(totAmt);
this.billingForm.patchValue({
products: {
totalAmount: totAmt
}
})
})
答案 0 :(得分:2)
您可能想在更改事件上添加一个功能。如下所示:
<div class="form-group col-md-4">
<label for="product">Product</label>
<select formControlName="pdt" class="form-control" **(change)="onChange($event)"** >
<option [value]="pdt.productPriceId" *ngFor="let pdt of productPrice">{{pdt.productName}} - {{pdt.size}}</option>
</select>
</div>
您应该能够在那里捕获新产品,并可以使用数据绑定更新其余字段。 希望对您有帮助!