Angular Reactive Forms提交报错TypeError及表单失效问题求助
Angular响应式表单验证失效+提交报错"Cannot read properties of null (reading '_syncPendingControls')"解决方案
核心提交报错修复
表单标签上的模板引用变量#ngForm与Angular内置的NgForm指令冲突,导致提交时无法找到正确的表单实例,触发空指针错误。
修改代码:
删除form标签的#ngForm属性:
<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
验证规则失效修复
1. 控件绑定不匹配
HTML中确认密码输入框的formControlName="cpassword",与TS中FormGroup定义的confirmPassword控件key不一致,导致该控件未关联到表单,验证完全失效。
修改代码:
将确认密码输入框的formControlName改为confirmPassword:
<input type="password" class="form-control" formControlName="confirmPassword">
2. 验证提示逻辑与文字错误
- mobile字段使用
Validators.maxLength(10),但错误提示判断的是minlength,逻辑颠倒 - mobile字段必填提示文字错误,误写为"Please provide password",应改为手机号相关提示
- 确认密码的minlength提示文字语法错误,且未添加对应验证规则
修复后的mobile验证提示:
<span *ngIf="!mobile.valid && mobile.touched" class="error-block"> <span *ngIf="mobile.hasError('maxlength')">Mobile number should not exceed 10 characters</span> <span *ngIf="mobile.hasError('required')">Please provide mobile number</span> </span>
修复后的确认密码验证提示+TS验证规则:
TS中给confirmPassword添加minLength验证:
confirmPassword: new FormControl('', [Validators.required, Validators.minLength(8)]),
HTML中修正提示文字:
<span *ngIf="!confirmPassword.valid && confirmPassword.touched" class="error-block"> <span *ngIf="confirmPassword.hasError('minlength')">Password should not be less than 8 characters</span> <span *ngIf="confirmPassword.hasError('required')">Please provide confirm password</span> </span>
验证效果
修复完成后,点击Save按钮不再出现控制台错误,所有验证规则会在输入框失焦或提交时正常触发,错误提示正确显示。
内容的提问来源于stack exchange,提问作者Wakashio1234
相关产品推荐
相关产品推荐

