I am playing with Angular form validation to implement a custom async validator which works well with Promises, but.. I would like to avoid Promises and use Observable to benefit from its useful methods and make it simpler.
I have done the following thing which is working well:
class OrderFormComponent{
issueSubject: FormControl;
static checkAsyncValue(val: string){
return new Observable(observer => {
setTimeout(() => { //Timeout just to simulate an async call
if( val.substr(0,2) != "#SUBJECT_" ) {
observer.next(false);
} else {
observer.next(true);
}
observer.complete();
}, 500);
});
}
constructor(fb: FormBuilder){
this.issueSubject = fb.control('', [Validators.required], []]);
const issueSubject = this.issueSubject;
let checkValue = function(value){
OrderFormComponent.checkAsyncValue(value).subscribe((result) => {
if (result !== true) {
issueSubject.setErrors({
notunique: true
});
}
});
}
issueSubject.valueChanges.debounceTime(500).distinctUntilChanged().subscribe(value => {
checkValue(value);
});
this.issueSubject.setValue('Test Bad Subject');
this.issueForm = fb.group({
subject: this.issueSubject
});
}
}
But, what I would like to do is to not be based on "valueChanges" and simplify things by adding a custom validator directly in the async validators array of the FormControl as explained below:
this.issueSubject = fb.control('', [Validators.required], [
//Adding here something like OrderFormComponent.checkAsyncValue
]]);
Please note I would like to keep the usage of the following:
debounceTime(500).distinctUntilChanged()
Is there a way to do it or is there mandatory to be based on valueChanges Observable?
EDIT: Something to add, one important drawback with my example is that the 'pending' property of the form won't be set while doing the custom asynchronous validation
Thank you in advance