請幫助理解。我正在嘗試爲被動表單編寫自定義驗證器。爲什麼表單值對象爲空?
組件:
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