Hacker
Hacker

Reputation: 7906

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

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);

Upvotes: 27

Views: 25375

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

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()

Upvotes: 23

Javier González
Javier González

Reputation: 2095

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();
     });

Upvotes: 7

Related Questions