Utilizing Angular 2 Reactive Forms alongside Typescript, my template structure is as follows:
<form [formGroup]="form">
<div class="M">
<div class="X">
<!-- I would like to avoid adding (change)="onChanged()" on all inputs -->
<input class="A" formControlName="MXA" />
<input class="B" formControlName="MXB" />
<input class="C" formControlName="MXC" />
</div>
<div class="Y">
<input class="A" formControlName="MYA" />
<input class="B" formControlName="MYB" />
<input class="C" formControlName="MYC" />
</div>
</div>
<div class="N">
<div class="X">
<input class="A" formControlName="NXA" />
<input class="B" formControlName="NXB" />
<input class="C" formControlName="NXC" />
</div>
<div class="Y">
<input class="A" formControlName="NYA" />
<input class="B" formControlName="NYB" />
<input class="C" formControlName="NYC" />
</div>
</div>
</form>
Accompanied by the component class:
export class MyCompoenent {
public form: FormGroup;
onInit() {
this.form = new FormGroup({
MXA: new FormControl(),
MXB: new FormControl(),
MXC: new FormControl(),
MYA: new FormControl(),
MYB: new FormControl(),
MYC: new FormControl(),
NXA: new FormControl(),
NXB: new FormControl(),
NXC: new FormControl(),
NYA: new FormControl(),
NYB: new FormControl(),
NYC: new FormControl(),
});
this.form.valueChanges.subscribe((p) => {
/* Unsure which input has been altered here */
});
this.form.get('MXA').valueChanges.subscribe((p) => {
/* Prefer not to subscribe to each individual input like this, especially with numerous inputs */
});
}
}
My goals are as follows:
1. There are four divs each containing three inputs; these inputs are related by the equation A+B=C. When one input is altered, it should check if another input in the same div has a provided value, and if so, calculate the third input accordingly.
For instance, if the value of input M => X => A is 2 and the user enters 3 in M => X => B, then M => X => C should automatically be set to 5.
2. If one input changes, it should update another input within the SAME grandparent div that shares the same class.
For example, if the value of input M => X => A is set to 5, then 5 should also be set in the input M => Y => A.
In the context of jQuery, achieving this is simple as a single binding can be applied to all inputs, allowing navigation within the DOM from the triggered input. However, I am seeking the proper Angular approach. The use of this.form.valueChanges() doesn't specify the changed input, and I am reluctant to subscribe to each input individually or add bindings to every input within the Angular template. I want to avoid excessive work, and refrain from using methods like getElementsByClassName, which is more familiar in jQuery. Any suggestions?
Thank you for your assistance!