angular - 以角度方式提交后如何重置表单中的错误?
问题描述
我在表单中手动设置错误验证,使用setErrors
.
问题是提交发生时错误不清楚。
我也不想遍历所有控件并将错误设置为 null- 因为它取消了控件上的其他错误。
只有一次我设置了错误,下次我不设置错误。我不想自己删除它我需要一些来自角度的功能来默认更新验证。
我尝试添加:{ updateOn: "submit" }
不清除错误。角度应该知道他没有任何验证。所以第二次需要消除错误。所以这不会发生。
这是我的代码。如何更新/触发表单验证以消除错误?
import { Component } from "@angular/core";
import { FormGroup, FormControl } from "@angular/forms";
@Component({
selector: "app-root",
template: `
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName" required />
<div *ngIf="firstname.hasError('foo')">foo error!!</div>
<div *ngIf="firstname.hasError('required')">required</div>
</label>
<label>
Last Name:
<input type="text" formControlName="lastName" />
</label>
<button type="submit">submit</button>
</form>
`
})
export class AppComponent {
title = "CodeSandbox";
profileForm = new FormGroup({
firstName: new FormControl(""),
lastName: new FormControl("")
});
get firstname() {
return this.profileForm.controls["firstName"];
}
showFooError = true;
onSubmit() {
console.log("in submit");
if (this.showFooError) {
this.profileForm.controls["firstName"].setErrors({ foo: true });
this.showFooError = false;
}
}
}
解决方案
updateOn: 'blur'
并且 updateOn: 'submit'
是我们在使用 Angular 时真正渴望的选项Forms
。
所以试试这个:
app.component.ts
this.userForm = this.fb.group(
{
name: ["", [Validators.required]],
email: ["", [Validators.required, Validators.email]]
},
{ updateOn: "submit" }
);
或者
this.userForm = this.fb.group(
{
name: ["", [Validators.required]],
email: ["", [Validators.required, Validators.email]]
},
{ updateOn: "blur" }
);
有关更多信息,请参阅本文:模糊和提交的 Angular 表单验证
推荐阅读
- javascript - 如何提交某种类型的表格
- android - 在 android 中使用 volley 库解析嵌套的 JSON 数组
- javascript - 如何将 API 生成的 JavaScript 变量作为表单的一部分传递给 php 变量?
- c++ - 从终止处理程序访问所有未捕获的异常
- r - 如何在管道工 API 中返回特定的错误代码?
- reactjs - 如何使用单选按钮更改此状态
- c# - 如果名称与字段名称不同,如何通过反射获取字段值
- module - 如何在运行时分发和交换业务逻辑?
- java - 如何删除java中的空值,例如(,,,test,tester,,java_test,,,)
- node.js - 如何在端口 443 上运行 nodejs 应用程序