Using Angular 7, none of the solutions presented here helped me.
I had to handle my error manually in my custom validator, which works with multiple form fields.
The example below checks to see if the difference between the two form fields is large enough. There are also several other validators in the form fields under consideration (lte, gte), so the elimination of all errors with setError (null) was excluded, and the attempt to remove my specific error with setError ({minDifference: null}) always left formControl in an invalid state .
minDifference(firstKey: string, secondKey: string, minDifference: number) { return (c: AbstractControl): {[key: string]: any} => { if (!c.get(firstKey).value || !c.get(secondKey).value || Math.abs(c.get(firstKey).value - c.get(secondKey).value) >= minDifference) { // If there is only one error and it this one then remove all errors from the control (removing 1 does not work) if (c.get(secondKey).hasError('minDifference')) { // If previously our error has been set, remove it. delete c.get(secondKey).errors.minDifference; // If no errors remain after, set the control to be valid. if (Object.keys(c.get(secondKey).errors).length === 0) { c.get(secondKey).setErrors(null); } } return null; } // Condition was not met, add our error to the alreadying existing ones. c.get(secondKey).setErrors( {...c.get(secondKey).errors, ...{ minDifference: true}} ) } }
Honestly, I do not really like my solution, I expected that I could solve it much easier, but I could not find a way to do this.
source share