I use Angular 2 Reactive Forms with Typescript. I have a template like this:
<form [formGroup]="form">
<div class="M">
<div class="X">
<!-- I dont want to put (change)="onChanged()" on every 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>
and 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) => {
/* I dont't know which input has been changed here */
});
this.form.get('MXA').valueChanges.subscribe((p) => {
/* I dont't want to subscribe to every individual input like this, its not good solution when there is too many inputs */
});
}
}
What I want is:
1. There are four div of three inputs, the 3 inputs have a relationship A+B=C, whenever one of the input change, it should check in the same div if another input has value, if it has, then calculate the third input.
e.g. the value of the input M => X => A is 2, then the user enter 3 in M => X => B, then the M => X => C is set automatically to 5
2. If a input change, it should update another input which has the same class in the SAME grand parent div.
e.g. the value of the input M => X => A is set to 5, then should set 5 to the input M => Y => A
Thiking in jquery way it is easy because I can do a single bind to all inputs and I can know which input trigger the change event, then I can navigate in the DOM from the triggered input.
But I want know how to do it properly in Angular way. this.form.valueChanges() don't show which input has been changed, and I don't like to subscribe each input separately, don't like to put some bindings in every input in the angular template, because if there are too many inputs I need to do many work, and not want to use something like getElementsByClassName which is "jquery way", any idea ?
Thanks in advance!