Angular Reactive Form中FormGroup新增错误时视图未更新
问题核心根因
- 外层错误提示容器的渲染逻辑存在设计缺陷:容器的显示条件写死为
!confirmPassword.valid && confirmPassword.touched,当用户在confirmPassword输入任意非空内容时,控件自身绑定的required校验会直接通过,控件本身的valid状态切换为true,此时外层判断的!confirmPassword.valid条件不成立,整个错误提示块被直接隐藏,块内用于判断表单组级校验错误的子逻辑根本没有执行渲染的机会。 - 自定义密码一致性校验是挂载在FormGroup层级的,返回的
notmatched错误属于表单组级别错误,不属于confirmPassword单个控件的错误范畴,因此控件自身的valid状态无法感知这一组级别的校验结果,造成逻辑判断错位。
修复方案
调整视图层渲染逻辑
移除外层提示块中对!confirmPassword.valid的强绑定判断,只要confirmPassword控件被触碰过,就保留错误提示块的渲染权限,分别判断两类错误的展示条件:
<label for="cpassword" class="form-label">Confirm Password</label> <input type="password" class="form-control" formControlName="confirmPassword"> <span *ngIf="confirmPassword.touched" class="error-block"> <span *ngIf="confirmPassword.hasError('required')"> Please confirm password </span> <span *ngIf="!confirmPassword.hasError('required') && regForm.hasError('notmatched')"> Password not matched </span> </span>
(可选优化)调整校验挂载层级
如果希望confirmPassword控件自身的valid状态就能感知密码匹配的校验结果,可以把原组级别的自定义校验,挪到confirmPassword控件层级,通过控件的父级引用获取password字段的值做比对:
- 移除FormGroup初始化时传入的组级校验器
this.passwordMatchingValid - 给confirmPassword控件追加自身的自定义校验逻辑,示例代码:
ngOnInit() { this.regForm = new FormGroup({ userName: new FormControl('Mark', Validators.required), email: new FormControl(null, [Validators.required, Validators.email]), password: new FormControl(null, [Validators.required, Validators.minLength(8)]), confirmPassword: new FormControl(null, [ Validators.required, (control: FormControl) => { // 拿到同组的password字段值做比对 const pwdValue = control.parent?.get('password')?.value; return pwdValue === control.value ? null : { notmatched: true }; } ]), mobile: new FormControl(null, [Validators.required, Validators.minLength(10)]), }); }
调整后confirmPassword控件的valid状态会直接覆盖密码匹配的校验结果,原有基于控件状态编写的错误判断逻辑无需额外改动即可正常运行。
内容的提问来源于stack exchange,提问作者DeadInsideProgrammer
相关产品推荐
相关产品推荐

