在 angular 中写入验证器时无法读取未定义的 属性 'get' 6
Cannot read property 'get' of undefined while writing validator in angular 6
我正在尝试编写一个验证器来匹配 angular 6 中的密码,下面是组件 class
的代码
export class comnentClass implements OnInit {
addAccountForm = new FormGroup({
"username": new FormControl('',
[ Validators.required],this.shouldContainUniqueUsername.bind(this)),
"password": new FormControl('', Validators.required),
"confirmPassword": new FormControl('',[Validators.required,this.checkPasswords.bind(this)]),
});
get username() {
return this.addAccountForm.get('username');
}
get password() {
return this.addAccountForm.get('password');
}
get confirmPassword() {
return this.addAccountForm.get('confirmPassword');
}
onSubmit() {
}
checkPasswords(control: AbstractControl) {
let pass = this.password;
console.log("password is "+pass)
return pass === control.value ? null : { notSame: true }
}
}
每次 angular 加载组件 class 时,我都会遇到异常
core.js:1598 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
at SysAdminComponent.get [as password] (sys-admin.component.ts:53)
如何在编写验证器匹配密码时获取其他输入类型的值?
替换下面的密码代码 属性 获取方法。
get password() {
return this.addAccountForm ? this.addAccountForm.get('password') : null;
}
问题是您在 confirmPassword 属性 中绑定了 checkPasswords 验证器,并且在此方法中您调用了 password 属性 formcontrol。因为 'addAccountForm' 未定义。
请检查 stackblitz
上的工作样本
我建议如果你想比较密码,那么请参考这个答案。
如有任何困惑,请告诉我。
我正在尝试编写一个验证器来匹配 angular 6 中的密码,下面是组件 class
的代码export class comnentClass implements OnInit {
addAccountForm = new FormGroup({
"username": new FormControl('',
[ Validators.required],this.shouldContainUniqueUsername.bind(this)),
"password": new FormControl('', Validators.required),
"confirmPassword": new FormControl('',[Validators.required,this.checkPasswords.bind(this)]),
});
get username() {
return this.addAccountForm.get('username');
}
get password() {
return this.addAccountForm.get('password');
}
get confirmPassword() {
return this.addAccountForm.get('confirmPassword');
}
onSubmit() {
}
checkPasswords(control: AbstractControl) {
let pass = this.password;
console.log("password is "+pass)
return pass === control.value ? null : { notSame: true }
}
}
每次 angular 加载组件 class 时,我都会遇到异常
core.js:1598 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
at SysAdminComponent.get [as password] (sys-admin.component.ts:53)
如何在编写验证器匹配密码时获取其他输入类型的值?
替换下面的密码代码 属性 获取方法。
get password() {
return this.addAccountForm ? this.addAccountForm.get('password') : null;
}
问题是您在 confirmPassword 属性 中绑定了 checkPasswords 验证器,并且在此方法中您调用了 password 属性 formcontrol。因为 'addAccountForm' 未定义。
请检查 stackblitz
上的工作样本我建议如果你想比较密码,那么请参考这个答案
如有任何困惑,请告诉我。