I have a directive appValidateOnChange
that implements
@HostListener('focus') onFocus() {
this.validators = this.formControl.control.validator;
this.asyncValidators = this.formControl.control.asyncValidator;
this.formControl.control.clearAsyncValidators();
this.formControl.control.clearValidators();
}
@HostListener('change') onChange() {
this.formControl.control.setAsyncValidators(this.asyncValidators);
this.formControl.control.setValidators(this.validators);
this.formControl.control.updateValueAndValidity();
}
The goal is to wait for the user to finish his input before validating it. I'm calling it simply like this
<input
type="text"
class="form-control"
id="field"
name="field"
[ngModel]="fieldValue"
#fieldName="ngModel"
required
minlength="8"
(change)="updateField(fieldName)"
appValidateOnChange>
In the updateField
function I have
if(!field.valid)
return false;
The problem is, there is a race condition between the two change
events.
Sometimes everything works as intended, because the directive's event triggers first, and some other times validation is ignored, since the directive's event triggers second.
How can I resolve that? I would like to avoid setTimeout
.