Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Abstract control remove error

Tags:

angular

I want a way to remove a specific error from a form control and not clear all error.

control.setError({'firstError': true})

and to remove that specific error like

control.removeError({'firstError}) and not control.setError({null})

I tried

control.setError({'firstError': false})

but didn't work.

Any help. Thanks

angular 4.1.1

like image 634
phacic Avatar asked Jul 13 '17 00:07

phacic


4 Answers

You can remove like this:

control.setErrors({'firstError': null})
like image 44
CharanRoot Avatar answered Nov 12 '22 21:11

CharanRoot


You can remove error with:

control.setErrors({'firstError': null});

control.updateValueAndValidity();
like image 125
Swapnil Mahadik Avatar answered Nov 12 '22 23:11

Swapnil Mahadik


First, you should check your field for has this error. next, remove it. And for end you are need to update all errors in your controll.

Something like this in validator function:

if (control.hasError('firstError')) {
      delete control.errors['firstError'];
      control.updateValueAndValidity();
    }

Regards.

like image 27
Denis Anisimov Avatar answered Nov 12 '22 21:11

Denis Anisimov


Much has already been stated in other posts to this question (e.g. delete the error property (which still leaves the control flagged as invalid), issues with updateValueAndValidity() in changeHandlers (infinite loop) etc). Putting it all together I now use the below small function, which leaves other errors untouched and resets the invalid flag if no other errors remain:

removeFormControlError(control: AbstractControl, errorName: string) {
  if (control?.errors && control?.errors[errorName]) {
    delete control.errors[errorName];
    if (Object.keys(control.errors).length === 0) {
      control.setErrors(null);
    }
  }
}
like image 11
Dschuli Avatar answered Nov 12 '22 22:11

Dschuli