[英]Angular: Custom validator returning null makes Angular throw an error
When I try to return null while validating a FormControlObject the browser says that it can not read the property of [FormControlObject].errors.errorProperty because its null. 当我在验证FormControlObject时尝试返回null时,浏览器说它无法读取[FormControlObject] .errors.errorProperty的属性,因为它为null。 Am I missing here something?
我在这里想念什么吗? If I return { errorProperty: false } it all works.
如果我返回{errorProperty:false},则一切正常。
The code: 编码:
static passwordsShouldMatch(control: AbstractControl): ValidationErrors | null {
let newPassword = control.get('password');
let repeatedPassword = control.get('repeatedPassword');
if (newPassword.value !== repeatedPassword.value) {
return { passwordsShouldMatch: true };
}
return null;
}
SOLUTION: 解:
static passwordsShouldMatch(control: AbstractControl): ValidationErrors | null {
let newPassword = control.get('password');
let repeatedPassword = control.get('repeatedPassword');
if (newPassword.value !== repeatedPassword.value) {
return { passwordsShouldMatch: true };
}
return {passwordsShouldMatch: false};
}
I have commented out the solution to this problem, but following the documentation, you should be able to return null without a problem. 我已经注释掉了该问题的解决方案,但是按照文档操作,您应该可以毫无问题地返回null。 This question might be a duplicate to this thread , but since that was asked 9 months ago and also did not resolve this potential problem I think it is ok to ask again.
这个问题可能与该线程重复,但是由于9个月前曾提出该问题,并且也未解决此潜在问题,所以我可以再次提出该问题。
Problem reproduced: https://stackblitz.com/edit/angular-d5utxs 转载的问题: https : //stackblitz.com/edit/angular-d5utxs
Replace 更换
account.errors.passwordsShouldMatch
by 通过
account.hasError('passwordsShouldMatch')
As you can see in the documentation , the type of FormGroup.errors
is ValidationErrors | null
如您在文档中
FormGroup.errors
, FormGroup.errors
的类型为ValidationErrors | null
ValidationErrors | null
. ValidationErrors | null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.