Angular2 reactive forms delete error

Arman Gevorgyan picture Arman Gevorgyan · Apr 17, 2017 · Viewed 34.3k times · Source

I´m trying to set a form control status to valid

this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true})

now I want delete this error.

Answer

karoluS picture karoluS · Aug 13, 2018

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});
}