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

时间:2018-09-08 13:49:52

标签: angular typescript angular-reactive-forms

我正在尝试为密码创建自定义验证器,但我不明白为什么会出现以下错误  错误TypeError:无法读取未定义的属性'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);
}
}
}

2 个答案:

答案 0 :(得分:1)

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

我将添加一个子表单组的内容,该组既可以跟踪密码的值,又可以确认密码,但是如果您想走这条路,请修改代码,如下所示:

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

然后,您将使用parent访问表单组。另外,您需要返回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

但是,与此相关的是,我们需要记住,如果用户在修改Confirmpassword后修改了密码字段,并且密码不匹配,则该表格仍被视为有效。这是避免这种情况的一种方法:password and confirm password field validation angular2 reactive forms

答案 1 :(得分:0)

您可以使用 input .root 获得对控件父级(您的registerForm)的访问权,尝试此操作,无需使用f函数

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

...

#!/bin/bash
    CONFIG=app.conf
    myuser=$(awk '/^\[user1\]/{f=1} f==1&&/^user/{print $3;exit}' "${CONFIG}")
    mypassword=$(awk '/^\[user2\]/{f=1} f==1&&/^password/{print $3;exit}' "${CONFIG}")
    echo $myuser
    echo $mypassword