patchvalue or setvalue of formbuilder does not mark field as dirty or touched
Asked Answered
R

2

27

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);
Riane answered 19/12, 2017 at 18:12 Comment(0)
W
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()
Weariless answered 19/12, 2017 at 19:6 Comment(4)
But this wont mark the field whose value got changed to dirty right?Riane
I demonstrated form level dirty thing. You can do it on field level as wellWeariless
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.Tribromoethanol
@AntónioQuadrado Only user interaction sets the dirty flag. This is intentional. See this discussion: github.com/angular/angular/issues/9768Streeto
D
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();
     });
Doorframe answered 6/11, 2018 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.