// import NgForm
import { NgForm } from '@angular/forms';
// get the passed in variable from the html file
submit(myForm: NgForm): void {
console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);
// This is the key!
myForm.resetForm();
console.log(myForm.form.status, myForm.form.dirty, myForm.form.pristine, myForm.form.untouched, myForm.submitted, myForm.dirty, myForm.pristine, myForm.untouched);
}
@ViewChild('myForm') myForm: NgForm;
formGroup = new FormGroup({...});
submit() {
if (this.formGroup.pristine ||
this.formGroup.untouched ||
!this.formGroup.valid
) {
return;
}
.... do with form data
this.formGroup.reset();
this.myForm.resetForm();
}
10 回答
似乎还没有支持。我看到的一种解决方法是在提交后重新创建表单,这显然是繁琐和丑陋的。
也可以看看
https://github.com/angular/angular/issues/6196
https://github.com/angular/angular/issues/4933
https://github.com/angular/angular/issues/5568
https://github.com/angular/angular/issues/4914
以下是它目前如何与 Angular 4.1.0 - 5.1.3 一起使用:
from.resetForm()
我已经尝试了很多东西,我发现实际上将 form.submitted 重置为 false 的唯一方法如下:
在模板中,将表单发送到提交函数:
在 component.ts 文件中,具有以下内容:
console.log 值输出以下内容 - 请注意它会重置所有值。
VALID true false false true true false false
INVALID false true true true false false true
我在 RC.5 中这样做,我在模板中定义我的表单元素。
通过表单提交或用
ViewChild
观看它根本不起作用,这对我来说已经足够了。在更新的版本中(在我的例子中是 Angular 2.4.8),这很简单:
将控件标记为 prestine,因此再次有效。
从Benny Bottema 的回答开始,我能够在 Angular 6 中使用 resetForm()重置包含验证的表单。
这对我来说在 Angular 5 中使用模板驱动的表单(它不适用于被动表单)
这会重置表单值和验证。
如果你使用 model-driven forms i.e ngFormModel,提交后再次定义 controlGroup 会解决 this.Refer 这个链接
我最近认为这是因为目前(2016 年 5 月)尚未构建到 Angular2 中。
考虑到用户无法输入'undefined'或'null',验证主要用于向用户显示表单错误,然后将控件值重置为 Null
在决定仅通过添加在 UI 中显示控制错误时,您将需要添加此条件
(此检查是因为 Validators.Required 将空白内容视为有效)
希望这可以帮助。
我很感激每个人的答案。他们指出了我正确的方向。
带有角度材料的角度 6
然后