多个表单字段上的 Angular 异步验证器

Nit*_*ite 4 asynchronous angular-validation angular

我正在尝试在 FormControl 上实现异步验证器,它依赖于同一表单的另一个字段的值。为了以同步方式完成相同的任务,我只需创建一个验证器函数,并将其附加到 FormGroup 验证器。

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

现在,我应该怎么做才能以异步方式完成完全相同的事情(基本上是调用执行 httpClient 请求的服务)?

Angular 文档中提供的所有示例都与单个 FormControl 验证相关(据我所知,如果将验证器附加到单个 FormControl,则无法访问其他 FormControl)https://angular.io/guide/form-validation#creating-asynchronous-验证者

谢谢

Nar*_*ali 6

你可以通过parent属性访问该控件的父窗体,然后得到你想要的控件!

@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))
    );
  }
}
Run Code Online (Sandbox Code Playgroud)