0

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.

karldegen
  • 113
  • 8
  • To play around, I created a stackblitz example, that shows no reason, why a FormControl gets dirty without user interaction: [link](https://stackblitz.com/edit/angular-ivy-form-control-flags). Stackblitz is Angular 10, we use still Angular 7 – karldegen Nov 02 '20 at 18:44

2 Answers2

1

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.

Edward
  • 1,076
  • 1
  • 12
  • 24
  • Thx @Edward, {emitEvent:false} is a good point. The bubbleing of 'dirty' from FormControl to FormGroup I'm aware of. Only some FomrControls inside FormGroup are dirty. – karldegen Nov 02 '20 at 18:51
  • Thx @Edward, it was the missing of { emitEvent: false } at a certain position in code. – karldegen Nov 04 '20 at 09:21
0

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

Flecibel
  • 166
  • 2
  • 11
  • I called markAsPristine() on the whole FormGroup after setting all the new values – karldegen Nov 02 '20 at 18:46
  • `markAsPristine(opts: { onlySelf?: boolean; } = {}): void` Without that flag you will only mark the current AbstractControl as pristine. see: https://angular.io/api/forms/AbstractControl#markaspristine – Flecibel Nov 12 '20 at 11:11