使用 FormGroup、FormBuilder 和 Validators 时更改 angular11 表单验证状态
Change angular11 form validation status when using FormGroup, FormBuilder and Validators
onblurRePass(event:any){
this.valOfRePass = this.empProperties.repassword;
console.log("Pass Val: "+this.valOfPass + " RePass Val: "+this.valOfRePass);
if(this.valOfPass == this.valOfRePass){
this.matchPassword = 'matched';
this.addForm.status = 'VALID'; // need to change this status
}
else{
this.matchPassword = 'unmatched';
this.addForm.status = 'INVALID'; //need to change this status
}
}
错误:无法分配给 'status',因为它是只读的 property.ts(2540)
您有几个选项可用。
- 如果表格有错误则无效,因此您可以简单地使用
setErrors()
更新表格
onblurRePass() {
this.valOfRePass = this.empProperties.repassword;
console.log(
'Pass Val: ' + this.valOfPass + ' RePass Val: ' + this.valOfRePass
);
if (this.valOfPass == this.valOfRePass) {
this.matchPassword = 'matched';
this.addForm.setErrors(null)
} else {
this.matchPassword = 'unmatched';
this.addForm.setErrors({'mismatched': true})
}
}
- 另一种选择是简单地使用自定义验证器
实现此目的的最佳方法是创建自定义验证器并将其用于 FormGroup({})
本身,而不是密码的 FormControl()
。
此验证器 directive
class 将两个 FormControl()
作为输入并检查它们的值是否匹配。因此验证器必须比它正在验证的两个 FormControl()
处于更高级别。
希望本文对您的情况有所帮助。
onblurRePass(event:any){
this.valOfRePass = this.empProperties.repassword;
console.log("Pass Val: "+this.valOfPass + " RePass Val: "+this.valOfRePass);
if(this.valOfPass == this.valOfRePass){
this.matchPassword = 'matched';
this.addForm.status = 'VALID'; // need to change this status
}
else{
this.matchPassword = 'unmatched';
this.addForm.status = 'INVALID'; //need to change this status
}
}
错误:无法分配给 'status',因为它是只读的 property.ts(2540)
您有几个选项可用。
- 如果表格有错误则无效,因此您可以简单地使用
setErrors()
更新表格
onblurRePass() {
this.valOfRePass = this.empProperties.repassword;
console.log(
'Pass Val: ' + this.valOfPass + ' RePass Val: ' + this.valOfRePass
);
if (this.valOfPass == this.valOfRePass) {
this.matchPassword = 'matched';
this.addForm.setErrors(null)
} else {
this.matchPassword = 'unmatched';
this.addForm.setErrors({'mismatched': true})
}
}
- 另一种选择是简单地使用自定义验证器
实现此目的的最佳方法是创建自定义验证器并将其用于 FormGroup({})
本身,而不是密码的 FormControl()
。
此验证器 directive
class 将两个 FormControl()
作为输入并检查它们的值是否匹配。因此验证器必须比它正在验证的两个 FormControl()
处于更高级别。
希望本文对您的情况有所帮助。