Angular 2 - Remove validation error
I wrote a function to update the Validator rules on input if any option was selected using this method (forms are created using FormGroup):
onValueChanged(data : any) {
let appVIP1 = this.vip1TabForm.get('option1');
let appVIP2 = this.vip2TabForm.get('option2');
let appVIP3 = this.vip3TabForm.get('option3');
//Set required validation if data is 'option3'
if(data != 'option3') {
//Due to initialization errors in UI, need to start with the case
//That there are validations, check to remove them
appVIP1.setValidators([]);
appVIP2.setValidators([]);
appVIP3.setValidators([]);
}
else {
appVIP1.setValidators([Validators.required]);
appVIP2.setValidators([Validators.required]);
appVIP3.setValidators([Validators.required]);
}
}
And I am associating a call to this function with a click event on the radio buttons (I originally used the guide from this answer , but the onChange function was not communicating correctly).
This works great and if the user selects option 1 or 2, the checks are empty and will not run. If they choose option 3, validations are shown and the submission stops. However, I ran into an issue where the user submits, sees an error and falls back to option 1 or 2. While the validator is clearing, my form is still considered invalid. I have multiple input fields that I validate, so I cannot just set the form to valid if the validator is removed this way. How should I do it? Can I delete has-error
for one specific field in a form group?
source to share
If the correct validators are set, you can manually invokeAbstractControl#updateValueAndValidity
after selecting an option:
this.formBuilder.updateValueAndValidity();
(Where, of course, this.formBuilder
is your copy FormBuilder
.)
You can also call it directly on FormElements.
This is usually used to trigger validation after the value of a form element has been changed programmatically.
source to share