请帮助理解。我正在尝试为被动表单编写自定义验证器。为什么表单值对象为空?
组件:
private form: FormGroup;
ngOnInit() {
const this_ = this;
this.form = new FormGroup({
'email': new FormControl(null, [Validators.required, Validators.email]),
'password': new FormControl(null, [Validators.required, Validators.minLength(6)]),
'password2': new FormControl(null, [Validators.required, Validators.minLength(6), this_.comparePasswords]),
'name': new FormControl(null, [Validators.required]),
'agree': new FormControl(false, [Validators.requiredTrue])
});
}
comparePasswords(c: FormControl) {
console.log(c);
const hashStr = Md5.hashStr(c.value.password);
const hashStr2 = Md5.hashStr(c.value.password2);
console.log(hashStr, hashStr2);
return (hashStr === hashStr2) ? null : {
comparePasswords: {
valid: false
}
};
}
所有你需要连接的进口。加载页面后,浏览器控制台立即显示表单对象,其中值对象为空。
我无法检查函数comparePasswords()。
控制台显示如下:
ERROR TypeError: Cannot read property 'password' of null
而是用空的默认密码值新formcontrol的,你为什么不设置默认值为空字符串'“”'?我敢打赌,这是问题。 –
对不起,我没有看到@ I.R.R回答。评论 – Wallace