I have a custom async validator in a reactive form that needs to call out to a service to validate whether a name is unique.
Since validators are pure functions, there doesn't seem to be a good way to inject a provider such as HTTP to make these calls.
The code I currently have is returning a function that passes the service but this feels a tad hacky...
export function nameValidator(platformService: PlatformService): ValidatorFn {
return (control: FormControl): { [key: string]: any } => {
return userService.getUnique(control.value)
};
}
my question is there a better way?
Validators can be injectable directive classes when being used as directives in templates.
They are expected to be functions when they are specified directly in FormControl or FormBuilder
In order to make use of DI they should be useFactory or useClass providers and injected into a component:
@Injectable()
class NameValidator implements AsyncValidator {
constructor(private userService: UserService) {}
validate = (control: FormControl) => this.userService.getUnique(control.value);
}
...
new FormControl('', nameValidator.validate);
Notice that validate method is passed as a callback and should be either an arrow or be bound to class instance with bind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With