无法读取 属性 个未定义的反应形式

Cannot read property of undefined Reactive Forms

我正在尝试为密码创建一个自定义验证器,但我不明白为什么会出现以下错误 错误类型错误:无法读取未定义的属性'f'

下面是我的代码:

registerForm: FormGroup;
submitted = false;
constructor(private Auth:AuthService, private router:Router,private 
formBuilder:FormBuilder) { }

ngOnInit() {
this.registerForm = this.formBuilder.group({
  userName: ['', Validators.compose([Validators.required,Validators.minLength(6),Validators.maxLength(30),Validators.pattern('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')])],
  email: ['', Validators.compose([Validators.required, Validators.email])],
  password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
  cpassword: ['', Validators.required,passwordMatch()] //paswordMatch triggers the error
},);
}

get f() { return this.registerForm.controls; }

function  passwordMatch() { 
if(this.f != undefined){
let passwordInput = this.f.password,
   passwordConfirmationInput = this.f.cpassword;
if (passwordInput.value !== passwordConfirmationInput.value) {
 return passwordConfirmationInput.setErrors({notequal: true})
}
else {
   return passwordConfirmationInput.setErrors(null);
}
}
}

您可以使用 input .root 来访问控件的父级(您的 registerForm)试试这个,不需要 f 函数

 function  passwordMatch(input: FormControl) { 
  if(input.root != undefined){
  let passwordInput = input.root.controls.password,
  passwordConfirmationInput = input.root.controls.cpassword;
  if (passwordInput.value !== passwordConfirmationInput.value) {
   return passwordConfirmationInput.setErrors({notequal: true})
  }
  else {
    return passwordConfirmationInput.setErrors(null);
  }
 }

...

cpassword: ['', Validators.required, passwordMatch]

this 在您的函数中是 undefined,因此您不能引用它。

我会添加一个子表单组,它会跟踪密码和确认密码的值,但是如果你想走这条路,请修改你的代码:

// ...
// see the brackets also around the validators! No need to use Validators.compose
cpassword: ['', [Validators.required, passwordMatch]]
// ...

然后您将使用 parent 访问表单组。您还需要 return null(有效)或错误:

function passwordMatch(input: FormControl) {
  if (input.parent) {
    let passwordInput = input.parent.get('password');
    if (passwordInput.value !== input.value) {
      return { notequal: true }
    }
    else {
      return null;
    }
  }
}

演示: StackBlitz

但是,我们需要记住,如果用户在修改确认密码后修改了密码字段并且密码不匹配,则该表单仍将被视为有效。这是避免这种情况的方法: