我对angular 2/4和一般的web开发还不熟悉。我有一张表格,它收集购买表格中不同产品的信息。
我已经构建了一个变体的表单组的formarray,如下面的html所示。
<form [formGroup]="this.purchaseInvoiceItemVariantsForm" novalidate>
<div formArrayName="variants">
<div *ngFor="let variant of this.purchaseInvoiceItemVariantsForm.controls.variants.controls; let i = index">
<div [formGroupName]="i">
<md-input-container>
<input mdInput placeholder="Product Code" formControlName="productBarcode" class="input--small" [readonly]="this.mode == 'view'">
</md-input-container>
<md-input-container>
<input mdInput placeholder="Color" formControlName="variant1" class="input--small" [readonly]="this.mode == 'view'" required>
</md-input-container>
<md-input-container>
<input mdInput placeholder="Size" formControlName="variant2" class="input--small" [readonly]="this.mode == 'view'" required>
</md-input-container>
<md-input-container>
<input mdInput placeholder="MRP" formControlName="mrp" class="input--small" [readonly]="this.mode == 'view'">
</md-input-container>
<md-input-container>
<input mdInput placeholder="Purchase Price" formControlName="purchasePrice" class="input--small" [readonly]="this.mode == 'view'"
required>
</md-input-container>
<md-input-container>
<input mdInput placeholder="Sell Price" formControlName="sellPrice" class="input--small" [readonly]="this.mode == 'view'"
required>
</md-input-container>
<md-input-container>
<input mdInput placeholder="Quantity" formControlName="variantQuantity" class="input--small" [readonly]="this.mode == 'view'" required>
</md-input-container>
<md-input-container>
<input mdInput placeholder="Discount" formControlName="variantDiscount" class="input--small" [readonly]="this.mode == 'view'">
</md-input-container>
<button md-icon-button (click)="removeVariant(i)" color="warn" *ngIf="purchaseInvoiceItemVariantsForm.controls.variants.length > 1 && this.mode != 'view'"><md-icon>delete</md-icon></button>
</div>
</div>
现在,一旦用户添加了3个变体,我希望能够监听formcontrol“productbarcode”的valuechanges,以便从数据库中获取颜色和大小的详细信息。
有什么建议可以做到这一点吗?
提前谢谢!
当做,
纳维
最佳答案
我们可以做一个版本的valueChanges
,当variants
-数组长度为a>= 3
时开始监听。然后我们听条码的每一个变化。
我假设您有一个函数,可以在其中向variants
数组添加新控件,我们可以在那里实现它:
addVariant() {
// code here for adding control
// check length
if(this.purchaseInvoiceItemVariantsForm.get('variants').length >= 3) {
// iterate each object in array
for(let val of this.purchaseInvoiceItemVariantsForm.get('variants').controls) {
// listen to changes in each barcode, if change, do something!
val.get('productBarcode').valueChanges.subscribe(data => {
console.log(val.get('productBarcode').value)
// do something!
})
}
}
}
Demo