I´m trying to set a form control status to valid
this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true})
now I want delete this error.
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.
AFAIK, You really don't need to use setErrors method when you can create custom validators. You can easily create custom validators for your formControl or formGroup and inside your validator you just need to return a ValidatorFn and you shouldn't use setErrors method.
For more info about custom validator for FormGroup, I suggest you reading this article which solved my issue.
This is my working code:
registerationForm = this.formBuilder.group({
username: ['', [Validators.required, Validators.email]],
passwords: this.formBuilder.group(
{
password: ['', Validators.required],
confirmPassword: ['', Validators.required]
},
{
validator: matchPassword
}
),
policyAgreement: ['', Validators.required]
});
// Outside my component:
const matchPassword = (group: FormGroup) => {
const password = group.get('password').value;
const confirmPassword = group.get('confirmPassword').value;
return password != confirmPassword ? { matchPassword: true } : null;
};