Angular Reactive forms : how to reset form state and keep values after submit

前端 未结 7 1749
逝去的感伤
逝去的感伤 2020-12-29 18:42

In an Angular reactive form. How to reset only the state of form after successful submit?

Here is the process:

  • Create the form and
7条回答
  •  有刺的猬
    2020-12-29 19:27

    Caution for users of angular/material2

    There's an added complication if you're using angular material controls, with mat-error to display your errors. Such errors are displayed based on the result of an ErrorStateMatcher (in addition to any *ngIf you may have applied).

    The default ErrorStateMatcher displays errors if the following is true:

    isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean 
    {
       return !!(control && control.invalid && (control.touched || (form && form.submitted)));
    }
    

    So what this says is if the form has ever been submitted and a control becomes invalid (per validation rules) then the error will be displayed. This is often not what you want (especially if you're reading this question!).

    Looking at the source code - there isn't a way to set submitted = false unless you call resetForm on the ngForm directive (not the FormGroup object). Setting states as pristine or untouched don't reset submitted to false.

    If you're using mat-error you may find it easier to create your own ErrorStateMatcher (simple interface) for custom logic if this is an issue.

    Also note that ErrorStateMatcher is only in angular material - and not a part of standard angular forms.

提交回复
热议问题