0

I have created a custom validator in Angular. I am using an Angular service in the validator validateFund function.However, Angular is providing a new instance of the service; my validation always fails when I try to validate the data since the service instance is new and doesn't have the data that is present in other instance of the service.

Here's the validator:

export function validateFund(control: AbstractControl): ValidationErrors | null {
  const injector = Injector.create([{ provide: FundOrgService, deps: [] }]);

  const fundOrgService = injector.get(FundOrgService);
  console.log(fundOrgService.funds);
  const fund: Fund = control.value;
  const check = fundOrgService.getFundById(fund.portId);

  return fund && check ? null : { 'fund-validity': true };
}
Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72

1 Answers1

0

Just figured out the answer. Custom validators in Angular are pure JavaScript functions, you need to pass in the instance of the Angular Service ourselves.

 this.portId.setValidators([
   Validators.required,
   validateFund(this.fundService),
 ]);
Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72