3

What's the reasoning behind Angular's decision to not reset an input's class from ng-dirty to ng-pristine after the user manually set a field back to its initial value?

I want to execute my save logic only if the user actually changed some of the form's data. Is there a better way than to manually hold the initial state and check for differences on submit?

D.R.
  • 20,268
  • 21
  • 102
  • 205

1 Answers1

2

The status is dirty this means the user changed the value. Angular doesn't track the original value though and therefore can't tell if the original value was restored.

If you want to know if the value changed, you have to store the value and on submit compare yourself if it has changed.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • "The status is dirty this means the user touched the value." - isn't that what the states `ng-touched` and `ng-untouched` are for? Aren't you even implying this by saying "the user touched the value" :-) – D.R. Oct 11 '16 at 09:18
  • You are right, sorry. AFAIK it still doesn't keep the original value around to compare. `ng-touched` only checks if the control had the focus. – Günter Zöchbauer Oct 11 '16 at 09:21
  • Ok, that's really unfortunate. Do you know anything about the reasoning why they haven't included a change tracking feature? It is really cumbersome to write such logic for all my fields...a pity. I'll create a feature request. – D.R. Oct 11 '16 at 09:22
  • I guess it's too complicated considering `ngModel` supports custom components with any kind of value where it's unclear what "unchanged" means. But the API could be extended so that the component has to implement the comparison itself. – Günter Zöchbauer Oct 11 '16 at 09:27
  • http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – Günter Zöchbauer Oct 11 '16 at 09:33
  • Looks like http://stackoverflow.com/a/3198202/1400869 would be a reasonable comparison approach. – D.R. Oct 11 '16 at 09:36
  • 2
    I created an issue at https://github.com/angular/angular/issues/12213, in the meantime: thanks for elaborating the current possibilities. – D.R. Oct 11 '16 at 09:40
  • Unlikely the Angular2 team will add a dependency to lodash for this. – Günter Zöchbauer Oct 11 '16 at 09:40