Angular:自定义验证器返回 null 使得 Angular 抛出错误

Angular: Custom validator returning null makes Angular throw an error

当我在验证 FormControlObject 时尝试 return null 时,浏览器说它无法读取 [FormControlObject].errors.errorProperty 的 属性 因为它是 null。我在这里错过了什么吗?如果我 return { errorProperty: false } 一切正常。

代码:

    static passwordsShouldMatch(control: AbstractControl): ValidationErrors | null {
  let newPassword = control.get('password');
  let repeatedPassword = control.get('repeatedPassword');

  if (newPassword.value !== repeatedPassword.value) {
    return { passwordsShouldMatch: true };
  }
  return null;
}

解决方案:

    static passwordsShouldMatch(control: AbstractControl): ValidationErrors | null {
  let newPassword = control.get('password');
  let repeatedPassword = control.get('repeatedPassword');

  if (newPassword.value !== repeatedPassword.value) {
    return { passwordsShouldMatch: true };
  }
  return {passwordsShouldMatch: false};
}

我已经注释掉了这个问题的解决方案,但是按照文档,您应该能够 return null 而不会出现问题。这个问题可能与这个 thread 重复,但由于这个问题是 9 个月前提出的,而且也没有解决这个潜在的问题,我认为可以再问一次。

问题重现:https://stackblitz.com/edit/angular-d5utxs

替换

account.errors.passwordsShouldMatch

来自

account.hasError('passwordsShouldMatch')

正如你在the documentation中看到的,FormGroup.errors的类型是ValidationErrors | null