I am using angular 7, reactive form.
I have a requirement to check the existence of particular value on the server to make field valid/invalid.
Component Class:
Control:
valueControl = new FormControl("" ,Validators.required,
), [this.valueIsUnique.bind(this)]);
/**
* Validator to checking existance/uniqueness
* of entered value
* @param control
*/
valueIsUnique(control: AbstractControl): Promise<ValidationErrors|null> | null {
if (control && (control.value !== null && control.value !== undefined)) {
return new Promise((resolve, reject) => {
this.service.checkValueExists(control.value, this.organizationId).subscribe(res => {
{
if (res && res['data']) {
resolve({
unique: true
});
}
else {
resolve(null);
}
}
},
err=>
{
resolve(null);
});
});
}
}
**Service:**
checkValueExists(value:string) {
return this._http.get(`${API}/${value}/exists`, {
headers: ...
}
);
}
Now this works fine. But I don't want to make control mandatory i.e Validators.required. So as a hack I added Validators.minLength(1) as sync validation but that gives error:
ERROR Error: Expected validator to return Promise or Observable. at toObservable (forms.js:603) at Array.map () at forms.js:591 at forms.js:611 at Array.map () at _executeAsyncValidators (forms.js:611) at FormControl.asyncValidator (forms.js:591) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl._runAsyncValidator (forms.js:2535) at FormControl.push../node_modules/@angular/forms/fesm5/forms.js.AbstractControl.updateValueAndValidity (forms.js:2508) at FormControlDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormControlDirective.ngOnChanges (forms.js:4463)
Is there are way to add async validation without having to add sync validation as second parameter:
Took reference from this SO ques/ans