Merei, you have the option to utilize {updateOn:'blur'}
, please refer to the documentation
Alternatively, you can skip using a validator and instead verify isEmailExist during submission
You could also "check" the email with a debounceTime when the value changes. Suppose you have a variable called "check" and a control
check=false;
control=new FormControl('',Validators.required,this.customValidator().bind(this))
The bind(this)
allows you to access a variable within your component, so your customValidator could be structured like this
customValidator(){
return (control) => {
if (!this.check) //if the variable in component is false return of(null)
return of(null)
else { //else call the service
return this.usersService.getUserByEmail(control.value).pipe(
map(users => {
if (users.some(user => user.email.toLowerCase() === control.value.toLowerCase())) {
return { isExist: true };
} else {
return null;
}
})
)
}
}
}
Now, after setting up the FormControl, you can subscribe to valueChanges
this.control.valueChanges.pipe(debounceTime(300)).subscribe(_ => {
this.check=true;
this.control.updateValueAndValidity({emitEvent:false});
this.check=false;
})
In this stackblitz example, I demonstrate calling your service with a dummy function