Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 951
Hacker Avatar asked Dec 19 '17 18:12

Hacker


People also ask

What is the difference between SetValue and patchValue?

SetValue Vs PatchValue The difference is that with setValue we must include all the controls, while with the patchValue you can exclude some controls.

What is the use of patchValue in Angular?

patchValue()link Patches the value of the FormGroup . It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group.

What is the advantage of using FormBuilder?

The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl , FormGroup , or FormArray . It reduces the amount of boilerplate needed to build complex forms.


2 Answers

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()
like image 56
Pankaj Parkar Avatar answered Oct 05 '22 23:10

Pankaj Parkar


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();
     });
like image 42
Javier González Avatar answered Oct 06 '22 00:10

Javier González