Access service from Custom Validator in Angular Access service from Custom Validator in Angular typescript typescript

Access service from Custom Validator in Angular


You have to pass the service to the validator, there is no dependency injection here as this is not an Angular directive, it is a pure function. The way to do this is to use a factory method that accepts the service and creates a validator function.

export function titleValidator(dataService:DataService): ValidatorFn {  return (control: AbstractControl) => {    console.log(dataService.moviesArray) // now you can :)    // Test for control.value only, for eg:    if (control.value && dataService.moviesArray.includes(control.value))      return null;    else      return { 'movieNotFound' : { value: control.value } };  }}

Usage:

this.movieForm = this.fb.group({  title: ['', [         Validators.required,         titleValidator(this.dataService)  ]],  ...});

There is no need to check for the presence of control as Angular only calls the validator function with a valid control. Test only the value. More info here