I encountered a situation in one of my projects where I need to visually indicate if a field is correct or incorrect based on the value of another field. To better illustrate this issue, I have created an example here.
The main challenge: I am struggling to change the color status of an input based on the value of ANOTHER input.
To clarify the problem, let me walk you through it using images: Step one - I entered a larger number in the Smaller Value input and blurred it, resulting in an expected error:
https://i.sstatic.net/k6SUQ.png
Step two - I entered a bigger number in the Bigger Number input and blurred it, anticipating the Smaller Value input to turn green, but it remains red:
https://i.sstatic.net/zprUl.png
My desired outcome is as follows: Whenever the smaller value exceeds a certain threshold, its input should turn red, and when it's within the criteria, the input should be colored green.
This logic functions when I manually change the Smaller Value and blur the input. However, if I enter a smaller number in the Bigger Number input, the Smaller Value input fails to transition from green to red as expected.
Here is the form and validator function I am utilizing:
this.thisForm = new FormGroup({
smallerValue: new FormControl('', [
this.validateSuccessShortName.bind(this)
]),
biggerNumber:new FormControl('', [
Validators.required
])
});
}
validateSuccessShortName(control: AbstractControl) {
if (parseInt(control.value,10) > parseInt(this.biggerNumber, 10)) {
return {value: control.value};
}
return null;
}
In an attempt to manually trigger validation, I implemented the following function which successfully triggers validation, but unfortunately doesn't update the validation status of the Smaller Value input based on the Bigger Number input:
updateFields(){
for (const field in this.thisForm.controls) {
this.thisForm.controls[field].updateValueAndValidity();
}
For a more interactive demonstration of this issue, visit this STACKBLITZ.
If you require further information, feel free to reach out!