Using Günter Zöchbauer's answer this is how I implemented my validator to access services from inside the AsyncValidatorFn
...
IMHO it seems cleaner to let the DI inject the service dependencies directly into the validator class instead of passing the dependencies to a static method from the consumer component to create the AsyncValidatorFn
.
Create your injectable validator class
import { Injectable } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, ValidationErrors } from '@angular/forms';
@Injectable
export class UsernameValidator {
constructor(
private http: HttpService,
) { }
usernameExists: AsyncValidatorFn = (control: AbstractControl): Observable<ValidationErrors> => {
// access your HttpService here...
}
}
Provide validator for injection in your module declaration
@NgModule({
providers: [
UsernameValidator, // register your validator for injection
],
})
export class UserModule { }
Set validator function in your component form
constructor(
private formBuilder: FormBuilder,
private usernameValidator: UsernameValidator, // inject your validator
) { }
ngOnInit() {
this.form = this.formBuilder.group({
username: [
null, // initial value
[Validators.required], // sync validators
[this.usernameValidator.usernameExists], // async validators
],
});
}