我有一个带有FormAwway的表格,其中显示了所购买产品的内容,这是我的组成部分:
constructor() {
this.purchaseForm = new FormGroup({
id: new FormControl(null, Validators.required),
purchase: new FormControl(null, Validators.required),
date: new FormControl(null, Validators.required),
products: new FormArray([]),
});
}
public createNewLine(object: any = {}): FormGroup {
const newLine = new FormGroup({
index: new FormControl(null),
id: new FormControl(object.id, Validators.required),
id_product: new FormControl(object.id_produto, Validators.required),
quantity: new FormControl(object.quantidade, Validators.required),
value_unit: new FormControl(object.valor_unitario, Validators.required),
value_total: new FormControl(object.valor_total, Validators.required),
});
const formArray = <FormArray>this.purchaseForm.get('products');
newLine.get('index').patchValue(formArray.length);
newLine.valueChanges.pipe(debounceTime(400)).subscribe(value => this.updateProductValue(value));
return newLine;
}
private updateProductValue(object): void {
const quantity = parseFloat(object.quantity);
const value_total = parseFloat(object.value_total);
const formArray = this.purchaseForm.controls['products'] as FormArray;
object.value_unit = value_total / quantity;
formArray.at(object.index).patchValue(object);
}
当我用数量或总价值更改输入时,我需要更新该特定产品的单位价值。问题在于,当我进行计算并更新值时,它将检测为新的值更改并再次执行该函数,直到创建一个循环。
我在这里做错了什么?或者我需要采取什么措施来防止这种行为?除了此循环外,其他所有功能都按预期运行。
答案 0 :(得分:3)
尝试像这样更改最后一行:
formArray.at(object.index).patchValue(object, { emitEvent: false, onlySelf: true });