I've followed the official Angular2 tutorial for template forms, and I'm having some issues understanding what the native reset
JavaScript function does to Angular2 ngModel. While not explicitly stated in the official documentation, I believe that reset
sets input values to their default, which is null
?
So it seems, because in the example, we have a newHero
function:
newHero() {
this.model = new Hero(42, '', '');
}
and when we "reset" the form, this function gets called:
<button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">
New Hero (official)
</button>
Note that newHero
function sets properties name
and power
to empty string. However, since after this function executes, we reset the form as well heroForm.reset()
, the new object is as follows:
{ "id": 42, "name": null, "power": null, "alterEgo": null }
This is interesting, isn't it? Since null
is NOT EQUAL to empty string (Difference between null and empty string) I could claim that this is just wrong. But it's in the official Angular2 documentation, so I'm not sure - am I not getting this right?
I changed the order in which things are called to this:
<button type="button" class="btn btn-default" (click)="heroForm.reset(); newHero()">
New Hero (alt)
</button>
This actually produces the correct object, which is: { "id": 42, "name": "", "power": "" }
Now imagine if there would be a default value for the new object, let's say that name
changes to Jessica Alba
. Angular's official example would override this value to null, so it begs the question why even have a function to reset the model?
Here's the project with 2 buttons for reset, the official and alternative one (note the model
JSON at the top): https://plnkr.co/edit/1w2SSv8qxpOCjfDaJxPz?p=preview
So my question is: is the example in the documentation wrong, or am I missing something? Does the reset
function actually change values to null
?