25

I have a multi-step form where the user traverses back and forth to the form. I save the form data in service and when he comes back I use patchValue to patch all the data to form. I tried setValue also, but the form fields are not marked as either dirty or touched. How do I mark fields updated as dirty and touched?

this.formBuilder.patchValue(formData);
Pieter Buys
  • 1,280
  • 1
  • 10
  • 20
Hacker
  • 7,798
  • 19
  • 84
  • 154

2 Answers2

23

You could explicitly mark the form using markAsDirty() & markAsTouched() method over your form object. See API Here

this.formName.markAsDirty()
this.formName.markAsTouched()

Update

Angular 8 onwards you can use markAllAsTouched to mark all form field as touched

this.formName.markAllAsTouched()
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • But this wont mark the field whose value got changed to dirty right? – Hacker Dec 20 '17 at 02:51
  • I demonstrated form level dirty thing. You can do it on field level as well – Pankaj Parkar Dec 20 '17 at 04:23
  • 4
    I also came across this problem and despite being possible to use the methods that you referenced it seems like we shouldn't have to do it manually. My point is that would be good to have angular verifying if the new value is different from the old one and set the according flags automatically. – António Quadrado Aug 20 '18 at 10:57
  • 3
    @AntónioQuadrado Only user interaction sets the dirty flag. This is intentional. See this discussion: https://github.com/angular/angular/issues/9768 – Markus Pscheidt Dec 17 '18 at 09:19
7

the only solution i found for this issue it's.

 this.form = this.formBuilder.group({
      id:[null],
      name: ValidatorsUtil.name(),
      lastName: ValidatorsUtil.required(),
      email: ValidatorsUtil.email(),
      phone: ValidatorsUtil.required(),      
    });

this.form.setValue(this.client, {emitEvent: true});

Object.keys(this.form.controls).forEach( controlKey => {
       this.form.controls[controlKey].markAsDirty();
     });
Javier González
  • 1,999
  • 17
  • 18