模型驱动表单提交后如何清除表单? (Angular 2)

How to clear the form after submitting in model-driven form? (Angular 2)

模型驱动表单提交后如何清除表单?我必须使用 ngModel 吗?谢谢

<form [ngFormModel]="myForm" (ngSubmit)="onSubmit()">
    <input type="text" [ngFormControl]="name">
    <button type="submit">Submit</button>
</form>

.

myForm: ControlGroup;
name: AbstractControl;

ngOnInit()
{
    this.myForm = this._formBuilder.group({
        'name': [""]
    });
    this.name = this.myForm.controls['name'];
}


onSubmit() {
    this.name.value = ""; // This is not working.
}

您可以迭代 this.myForm.controls 中的控件并调用 updateValue()。否则参见 https://github.com/angular/angular/issues/4933

您所要做的就是重新初始化表单,如下所示:

this.myForm = this._formBuilder.group({
    'name': [""]
});

这会将 formControlName 字段重置为空

从更新的 angular2 版本开始,angular2 为我们提供了 reset 重置表单所有控件的功能,只需使用此语法即可。

this.Your_form_name.reset();

PS:在表单提交后,如果您重新初始化表单,它可能会清除一次值,但状态根本不会重置,我的意思是表单将不再处于污垢状态(验证的观点)。

有关更多详细信息,请参阅此处

https://angular.io/docs/ts/latest/guide/forms.html

如果您有一些服务器验证,另一种有用的方法是:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
    ...
</form>

import { NgForm } from '@angular/forms';
onSubmit(myForm: NgForm) {
    // do something and if no error
    myForm.reset();
}