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;