Issue
I have a form with a FormAwway where it shows the products within a purchase made, this is my component:
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);
}
When I change the input with the quantity or total value I need to update the unit value for that specific product. The problem is that when I do this calculation and update the value, it detects as a new value change and execute that function again, which creates a loop.
What am I doing wrong here? Or what do I need to do to prevent this behavior? Apart from this loop, everything else is working as expected.
Solution
Try to change your last line like this:
formArray.at(object.index).patchValue(object, { emitEvent: false, onlySelf: true });
Answered By - srjkaa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.