I recently added a button to a form to reset all its inputs to default values once it's clicked. But the button cleared all the inputs. It turned out to be that I set the button type to "reset" and that's what it is supposed to do. Below is what I did.
First I added a button to a form
<button type="reset" (click)="onButtonClick()"/>. Maybe you're not familiar with
(click)="onButtonClick()". I used Angular 2 here and what it means is to handle the click event in
onButtonClick. I set all the fields in the form to some default values which are not null or undefined. Guess what. All the inputs were blank after the button was clicked. While I expected they show some values. Though I debugged and made sure
onButtonClick() did what it's supposed to do. I didn't find why the inputs were cleared.
Since I used some component from Ionic Framework in the form, I wondered whether there's some bug in that component. To prove it or disprove it, I wrote a simplified code snippet in plunkr. To my surprise, it worked. I compared the simplified code and my original code and realized the only difference was I set type to reset in my code.
According to https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button, a reset button will
The button resets all the controls to their initial values.
It has effects on the form's inputs too. No wonder that I set the inputs to the default values and reset always clears all of them.
If you want to reset your form, don't add "reset" to the button unless you understand what it does. If you have encounter a problem, it's always a good idea to try it out in a simplified version of your code.