I have the following snippet of code used to validate password and password again fields in an Angular template driven form. The idea is that if the two fields are different an error is attached to both. If they're the same, no errors are removed from both.
validate(control: AbstractControl): ValidationErrors | null {
// The current value
let currentValue = control.value;
// Control.root exposes the parent element of the directory
let otherField : AbstractControl = control.root.get(this.compareTo);
if(currentValue && otherField && currentValue !== otherField.value) {
otherField.setErrors({"fieldsMismatch": true});
otherField.markAsTouched();
setTimeout(() => {
control.setErrors({"fieldsMismatch" : true});
control.markAsTouched()}
)
} else {
control.setErrors(null)
otherField.setErrors(null)
}
return null;
}
1) If I remove the logic to set the current element's (control) error from the setTimeout, it stops working. Why?
2) If I remove errors using
control.setError({"fieldsMismatch": null});
otherField.setError({"fieldsMismatch": null});
The error is removed from both. But, for the current field (control), the errors key is set to null, meaning that .ng-invalid is removed from the input tag. For otherField, errors is set to an empty object, meaning the input is still marked as invalid. Why? I can just set errors to null explicitly, but then if I had other validation that would also be removed.
Both objects are of type AbstractControl, so I don't get what drives the difference.