angularangular-template-form

Resetting an Angular form with a model


I want to be able to reset an Angular form with some default values for it's model

<form>
  <input type="text" name="text" [(ngModel)]="model.text">
  <button type="reset" (click)="resetModel()">Reset</button>
</form>

and in the component

model = { text: 'Test' };

resetModel() {
  this.model = { text: 'Test' };
}

This doesn't work as the reset happens after the model is set and text is set to null by the reset.

The only two things I can figure out are one use a timeout like we used to pollute our AngularJs apps with like

resetModel() {
  setTimeout(() => { this.model = { text: 'Test' }; });
}

https://stackblitz.com/edit/angular-5pdpml

or make the button a plain old button instead of a reset button and pass the form in to the reset method and call markAsUntouched and markAsPristine.

I don't really like either of these options.

I have tried giving the input a value so the reset has a default value but Angular still sets the model to null even though the input does have the text set by the reset.

Is there a way for a reset button to set a default form state rather than setting all of the bindings to null?


Solution

  • There is a way without using setTimeout. You can get the reference of the form and call either reset or resetForm methods (in this case both will work) to reset the value (and status).

    <form #myForm="ngForm">
      <input type="text" name="text" [(ngModel)]="model.text">
      <button type="button" (click)="myForm.reset({ text: 'Test' })">Reset</button>
      <!-- <button type="button" (click)="myForm.resetForm({ text: 'Test' })">Reset</button> -->
    </form>
    {{ model | json }}
    

    Here is the updated stackblitz.

    You should notice that the button is not of type reset but regular button, for some reason type reset doesn't work. I will research a bit more and hopefully find a reason why...

    EDIT: Apparently, when using button type=reset it automatically resets the form values to their default values (in case of the input control that would be the value defined in the value attribute). That seems incorrect in Angular form context and shouldn't be used (bit more about that here).

    Furthermore, it is not even recommended using reset buttons in forms (as per official documentation) therefore I am quite confident that it is correct to use type=button in this case.

    You should usually avoid including reset buttons in your forms. They're rarely useful, and are instead more likely to frustrate users who click them by mistake (often while trying to click the submit button).

    Finally, I will mention the difference between reset and resetForm. They are the same except that resetForm also affects the submitted state of the form (sets it to false). More about that here.