What exactly marks an Angular2 reactive FormControl as dirty beside user interaction?

1k Views Asked by At

This is a question to gain a deeper understanding of Angular Reactive Forms.

We're about to create a lot complex components with lots of FormControl objects in each dialog. Therfor many things are set dynamically at runtime for those FormControl objects:

  • data from model (obvious)
  • validation rules (via control.setValidators(valArray))
  • enablement/diablement (e.g. via control.disable())

Code examples are to large to show here.

The problem is: after setting all components to new values, validations and enablement and a final this.formGoup.marktAsPristine() some fields are still or again dirty

One thing is, that we still have some Angular typical concurrency topics to solve. So it's - in the moment - more than likely that after that this.formGoup.marktAsPristine() some concurrent activities are still running. But for my understanding of Angular:

What actions can set a FormControl again to dirty, if no user interaction took place so far?

Documentation and my quite fat Angular book could not explain it to me.

2

There are 2 best solutions below

2
On BEST ANSWER

according to the angular docs

A control is dirty if the user has changed the value in the UI.

FormControls don't update themselves without some interaction either from the user, or the code is somehow doing this. i.e. via markAsDirty()

Do keep in mind that the 'dirty' property, like the invalid property will bubble up. so if you are nesting FormGroup or FormArray, you may be seeing values at the top level that are reflective of nesting.

The fact that you mention concurrency makes me question if you are using the { emitEvent: false } option when setting the values of your control programmatically. i.e. when using patchValue

similarly making sure to use onlySelf where appropriate to reduce the amount of "bubbling up" that occurs.

2
On

Did you pass the options with {onlySelf: false}? Otherwise it will only mark that abstractcontrol as pristine.