1

Currently I'm trying to create a dynamic validation in Angular Forms and I found this Question.

Adding the error to the field

this.form.get('field').setErrors({ 'invalid': true });

Removing the error to the field

this.form.get('field').setErrors(null);

My question is how can I remove a specific error in the field? Example I have multiple setErrors and I only want to remove the invalid error

Elohist
  • 83
  • 1
  • 11
  • I'm afraid that you can not, setError replace all the errors. You can always use `setErrors(Validators.required)` or to have an array of errors `[Validators.required,Validators.minLenght(3)]` and use `setErrors(errorsArray)` but I suppose it's not you want – Eliseo Jun 24 '20 at 06:47

2 Answers2

2

I faced the same problem, and thought of two ways to do it:

1. Using delete

const control = this.form.get('field');
const error = 'invalid';

if (control.hasError(error)) {
  delete this.form.get('field').errors[error];
}

However, this may be slow.
You should also check that the error exists using hasError as the rest of your code may not work otherwise. I made this mistake and wasted hours trying to figure why my code wasn't working.

2. Using setErrors

const control = this.form.get('field');
const error = 'invalid';

{ [error]: _ignored, ...errors } = control.errors;
control.setErrors(Object.keys(errors).length ? errors : null);

Here I'm using ES6 destructuring assignment together with the spread syntax to get only the errors that the control should have.

Important:
When setting errors, make sure to check that errors isn't empty by checking Object.keys(errors).length is more than 0. An empty object looks like this: {}, and this may flag the field as erroneous since {} is coalesced into true.

The { [error]: _ignored, ...errors } syntax is useful for when error is a variable. I found myself using this when passing error as a parameter to a function. If 'invalid' isn't stored in a variable, you can use this instead:

{ invalid: _ignored, ...errors } = control.errors;
0

I believe this should work:

this.form.get('field').setError({'invalid': null})
  • Hi Ana it does not work. The invalid error is set to null, but the field detect that their is an error. I want to remove only an specific error because when I use the `setError(null)` even the `required` validation is removed. – Elohist Jun 24 '20 at 02:46