Angular Reactive Form提交两次且提交成功后仍显示无效错误如何解决
问题根因
- 两次提交的核心原因是未阻止表单的原生默认提交行为:Angular
ngSubmit触发自定义提交逻辑后,原生表单提交行为会额外执行一次,导致提交状态被重新标记为true - 仅调用
FormGroupDirective.resetForm()没有同步重置响应式 FormGroup 的控件值与校验状态,残留的校验状态会触发错误提示
修复方案
步骤1:修改模板提交事件绑定
传入事件对象,显式标记提交按钮类型:
<form [formGroup]="testForm" (ngSubmit)="onSubmit($event, formDir)" #formDir="ngForm"> <mat-form-field appearance="fill"> <mat-label>测试字段</mat-label> <input matInput formControlName="testField" [errorStateMatcher]="customMatcher"> <mat-error *ngIf="testForm.get('testField').hasError('required')">该字段为必填项</mat-error> </mat-form-field> <button mat-raised-button color="primary" type="submit">提交</button> </form>
步骤2:修改组件提交处理逻辑
import { FormGroupDirective } from '@angular/forms'; // 提交处理函数 onSubmit(event: Event, formDir: FormGroupDirective) { // 阻止原生表单提交,避免二次提交 event.preventDefault(); if (this.testForm.invalid) return; // 此处写你的业务提交逻辑,例如调用后端接口 console.log('表单提交成功'); // 同步重置响应式表单状态 + 表单指令的提交/触摸状态 this.testForm.reset(); formDir.resetForm(); }
内容的提问来源于stack exchange,提问作者Daniel McIntyre
相关产品推荐
相关产品推荐

