MrWolfZ / ngrx-forms

Enhance your forms in Angular applications with the power of ngrx

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Storing the default value to know if a pre-filled form has real changes

Balastrong opened this issue · comments

Is your feature request related to a problem? Please describe.
Sometimes a form does not come empty but is already filled with data (imagine editing an existing entity coming from the database).
If I edit a field and bring it back to the original value, ngrx-forms flags it as dirty because the value changes.

Describe the solution you'd like
It can be useful to add a defaultValue field to the store to keep track of the default value and compare it with the actual value to know if it's the default one or not.

The default value can be set with a new SetDefault action and a new isDefault boolean can be added.

Describe alternatives you've considered
The default value can also be stored by passing a boolean flag to SetValue.

Additional context
This also helps handle a Save button to enable it only if the form has changed from the default value.

Let me know if you find this idea worth the time, I can also come up with a PR so we have some code to discuss.

a couple available approaches come to mind - haven't tried them, but seem like they should work.

a) using createFormGroupState in your reducer to "reinitialize" the form, providing the value you want.
b) use markAsPristine after setting the value

Thank you for the reply!

This indeed works if you want to set a value at first, and have a clean state :)

However, if for example I type a letter and I delete it, the form is no longer set as Pristine so I don't know that the current value, in fact, is exactly the same as before.

However, if for example I type a letter and I delete it, the form is no longer set as Pristine so I don't know that the current value, in fact, is exactly the same as before.

I see, I understand better now. I would argue that's not typical form-control behavior, specifically in the angular forms space. The control at that point would in fact be touched & dirty NOT pristine

If I were trying to achieve this behavior, I would probably either set the defaultValue in my store (outside the form) or possible leverage userDefinedProperties for that value, and do a comparison in a updater function, and set the control back to pristine if the current value and default value are equal - but this could get expensive depending on the size of your form