I´m trying to set a form control status to valid
this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true})
now I want delete this error.
Angular tells you that it's better for you to use the ways it gives you to disable/enable form controls. You can enable/disable a form control by using the following ways: Instantiate a new FormControl with the disabled property set to true. FormControl({value: '', disabled: true}) .
Reactive forms provide access to information about a given control through properties and methods provided with each instance. These properties and methods of the underlying AbstractControl class are used to control form state and determine when to display messages when handling input validation.
Other solutions seem to not work. It looks like angular thinks the control is invalid as long as the errors property is not null.
As long as you want to remove just a single error and leave others there's no way to do it but manually. This function will remove only one error specified in the argument and leave others. It will also make sure that if you remove the last error the control will become valid.
// call it in validator function if control is valid removeError(this.currencyForm.controls['currencyMaxSell'], 'smallerThan'); // this function removes single error function removeError(control: AbstractControl, error: string) { const err = control.errors; // get control errors if (err) { delete err[error]; // delete your own error if (!Object.keys(err).length) { // if no errors left control.setErrors(null); // set control errors to null making it VALID } else { control.setErrors(err); // controls got other errors so set them back } } } // this function adds a single error function addError(control: AbstractControl, error: string) { let errorToSet = {}; errorToSet[error] = true; control.setErrors({...control.errors, ...errorToSet}); }
To remove only one form control error when performing manual validation, do the following:
this.myFormGroup.get('myControl').setErrors({'myCustomError':null})
This will only update the value for the specified error, and will not erase any previous validation you may have done, as opposed to setErrors(null)
, which nullifies the whole errors object for the control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With