Home > database >  Angular Async Validator on multiple form fields
Angular Async Validator on multiple form fields

Time:08-31

I'm trying to implement an Async validator on a FormControl which relies on the value of another field of the same form. To accomplish this same task in a Syncronous way, I would just create a validator function that I would attach to the FormGroup validators.

/**/
mySyncValidator(form: FormGroup): { [s: string]: boolean } {
    const field1 = form.get('field1').value;
    const field2 = form.get('field2').value;
    ...
};

Now, what should I do to accomplish the exact same thing in an Async way (basically calling a service performing an httpClient request) ?

All the examples provided in the Angular docs are relative to a single FormControl validation (afaik you cannot access other FormControls if you attach a validator to a single FormControl) https://angular.io/guide/form-validation#creating-asynchronous-validators

Thanks

CodePudding user response:

You can access the parent form of the control by using parent property, then get the control you want!

@Injectable({ providedIn: 'root' })
export class UniqueAlterEgoValidator implements AsyncValidator {
  constructor(private heroesService: HeroesService) {}

  validate(
    control: AbstractControl
  ): Observable<ValidationErrors | null> {
    const parent = control && control.parent;
    const anotherCtrl = parent.get('<insert-another-control-name>');
    return this.heroesService.isAlterEgoTaken(control.value, anotherCtrl.value).pipe(
      map(isTaken => (isTaken ? { uniqueAlterEgo: true } : null)),
      catchError(() => of(null))
    );
  }
}
  • Related