Angular Abstract Control remove error
I want to be able to remove a specific error from the form control and not clear the whole error.
control.setError({'firstError': true})
and remove this specific error like
control.removeError({'firstError}) and not control.setError({null})
I tried
control.setError({'firstError': false})
but doesn't work.
Any help. Thanks to
angular 4.1.1
source to share
First, you should check your field for this error. Then remove that. And to complete, you need to update all errors in your control.
Something like this in the validator function:
if (control.hasError('firstError')) {
delete control.errors['firstError'];
control.updateValueAndValidity();
}
yours.
source to share
Unfortunately it didn't work for me. I just used updateValueAndValidity () which is used to recalculate the value and validate. Below is my validator function that validates mine grossWeight
.
validateWeights(formGroup) {
let netWeight = formGroup.get('netWeight');
let grossWeight = formGroup.get('grossWeight');
if (parseFloat(netWeight.value) > parseFloat(grossWeight.value)) {
grossWeight.setErrors({ 'customError': true });
netWeight.setErrors({ 'customError': true });
} else {
if(netWeight.errors && netWeight.errors['customError']) {
netWeight.updateValueAndValidity();
}
if (grossWeight.errors && grossWeight.errors['customError']) {
grossWeight.updateValueAndValidity();
}
}
}
source to share
If we add and remove errors dynamically starting with Angular 8, the above examples just don't work. I add errors based on the state of the other controls. I have two clients defined with the same email address. This is the only solution I could find.
tap(duplicateError => {
/* Note to future self...
* I'm beginning to hate AbstractControl.errors.
* The email control can have multiple errors (required, email, and duplicate);
* The ONLY way to clear an error is to not have it in the object that is passed to the setErrors call.
* You CANNOT pass null or undefined! It will still be evaluated as an error!
* This is also true if there are NO errors AT ALL. You cannot pass setErrors({}) or the control will be
* invalid, even though there are no errors! You must call setErrors(null);
* This is stupid, but it the only way it works.
* This code is concerned with setting/removing the duplicate error.
*/
const email = this.form.get('email');
// Clone the existing errors
const existingErrors = { ...email.errors };
// Ensure that duplicate error is removed (we're in the change handler for the duplicate error)
delete existingErrors.duplicate;
if (duplicateError) {
// We have a new duplicate error, so add it.
email.setErrors({ ...existingErrors, duplicate: duplicateError.errorMessage });
} else if (Object.keys(existingErrors).length === 0) {
// We have NO errors, so pass null
email.setErrors(null);
} else {
// We have existing errors, but no new duplicate error. Pass the existing errors.
email.setErrors(existingErrors);
}
this.changeDetector.markForCheck();
})
source to share