FormGroup 获取字段值:TypeError:无法读取未定义的属性“get”

san*_*dum 5 angular-validation angular angular-forms

我正在尝试对“passwordConfirm”字段进行验证,但出现一个奇怪的错误:ERROR TypeError: Cannot read property 'get' of undefined 这是我的代码:

loginForm: FormGroup;


ngOnInit(){
    this.loginForm = new FormGroup({
      'email': new FormControl(null, [Validators.required, Validators.email]),
      'password': new FormControl(null, Validators.required),
      'passwordConfirm': new FormControl(null, [Validators.required, this.checkIfMatchingPasswords.bind(this)]),
    });
}



checkIfMatchingPasswords() {
    return this.loginForm.get('password').value === this.loginForm.get('passwordConfirm').value ? null : { notSame: true} // error
  }
Run Code Online (Sandbox Code Playgroud)

Per*_*xel 2

您尝试通过绑定this到验证器来实现的目标可能会失败,因为多个验证器函数被合并到上下文可能不同的单个函数中。

但是,如果您遵循验证器函数的足迹,则可以执行以下操作:

checkIfMatchingPasswords(control: AbstractControl): ValidationErrors | null {
    return control.root.get('password').value === control.value ? null : { notSame: true };
}
Run Code Online (Sandbox Code Playgroud)

诀窍是每个人都AbstractControl知道它的parentroot