I am currently utilizing Angular Reactive Forms to loop through an array of values and I want to include a total field after the Form Array that automatically updates whenever there are changes in the Form Array control values.
Here is some sample data:
primaryData = {
products: [
{
name: 'test-product',
unmoved: 21,
moved: 18
},
{
name: 'another-product',
unmoved: 18,
moved: 42
}
]
}
The process involves creating the Reactive Form Controls and Array like this:
setPrimaryQuantities() {
const control = <FormArray>this.primaryForm.controls.quantities;
this.primaryData.products.forEach(product =>
control.push(this.fb.group({
name: [product.name, Validators.required],
unmoved: [product.unmoved, Validators.required],
moved: [product.moved, Validators.required]
}))
)
}
ngOnInit() {
this.primaryForm = this.fb.group({
quantities: this.fb.array([]),
unmovedTotal: '',
movedTotal: ''
})
this.setPrimaryQuantities();
}
I need advice on the best way to ensure that my unmovedTotal
and movedTotal
Controls are updated whenever there are changes in the Array controls. You can view a demonstration of my structure on StackBlitz.