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);
SetValue Vs PatchValue The difference is that with setValue we must include all the controls, while with the patchValue you can exclude some controls.
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.
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.
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()
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With