Angular单提交按钮绑定两个表单,如何实现校验逻辑分离?
问题根因
- 提交逻辑中同时校验了
clusterForm和productFG两个表单的有效性,只要其中一个不符合校验规则就会终止提交 - 两个表单的错误提示共用了同一个
submitted状态标记,点击提交按钮时会同时触发两个表单的错误提示
修复方案
1. 修改TS代码
删掉对productFG的校验规则,同时新增单独的提交状态变量控制clusterForm的错误展示,避免和另一个表单的状态冲突:
// 新增变量,单独控制clusterForm的提交状态 clusterFormSubmitted = false; sendclusteridApi() { this.clusterFormSubmitted = true; // 仅校验clusterForm即可 if (this.clusterForm.invalid) { return; } const request = this.createRequest(); this.projectclosterservice.postStoryStatus(request).subscribe( (res: any) => { this.filtering = res["1tool-gitlab-pipeline"].data.filtering; this.clusterForm.reset(); this.formData.reset(); // 提交成功后重置提交状态 this.clusterFormSubmitted = false; }, (error) => {} ); }
2. 修改clusterForm对应的HTML代码
把错误提示绑定的状态换成新增的clusterFormSubmitted,避免提交时误触发productFG的错误提示:
<div *ngIf="clusterFormSubmitted && fclusterForm.clusternames.errors" class="error-feedback error"> <p *ngIf="fclusterForm.clusternames.errors?.required" class="text-danger "> Please select Cluster </p> </div>
可选优化
如果后续productFG有单独的提交场景,可给它也单独设置一个productFGSubmitted状态变量绑定到自身的错误提示逻辑中,避免两个表单的状态互相干扰。
内容的提问来源于stack exchange,提问作者Mercy
相关产品推荐
相关产品推荐

