Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: How do you mark FormGroup control dirty via `patchValue()`

Tags:

I am updating a Reactive FormGroup control value from my component via patchValue.

Ex:

this.myForm.patchValue({incidentDate:'2016-09-12');

This works great and triggers a valueChanges event, however this control's dirty property is still false.

I need the incidentDate control to be dirty so my validation logic knows to run against this control.

How do I update the value of a control from my component AND indicate that it is dirty?

Here is my validation logic:

onValueChanged(data?: any) {
    if (!this.myForm) {
      return;
    }
    const form = this.myForm;
    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages: any = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
}
like image 588
rynop Avatar asked Oct 01 '16 03:10

rynop


People also ask

How do you make angular forms dirty?

You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.

How do you set a value control in a FormGroup?

The setValue accepts an object that matches the structure of the FormGroup with control names as keys. The object supplied to setValue should exactly match the structure of this form group i.e. the object should contain each and every form control names as keys. Find the setValue method declaration from Angular doc.

What is the use of PatchValue?

The PatchValue is used to update only a subset of the elements of the FormGroup or FormArray . It will only update the matching objects and ignores the rest.


2 Answers

I usually do this:

this.formControl.markAsDirty()

Or in your case it could be:

this.myForm.get('incidentDate').markAsDirty()
like image 168
Harry Ninh Avatar answered Sep 19 '22 14:09

Harry Ninh


If you have a group or array that you need to mark as dirty you can use this

export class Helpers {
/**
   * Loop and touch all it has
   *
   * @param {FormGroup} formGroup
   * @param func << function name: [markAsTouched, markAsUntouched, markAsDirty, markAsPristine, markAsPending
   * @param opts
   *
   */
  public static touchAll(formGroup: FormGroup|FormArray, func = 'markAsDirty', opts = {onlySelf: false}): void {
    mapValues(formGroup.controls, (c, i) => {
      if (c instanceof FormGroup || c instanceof FormArray)
        Helpers.touchAll(c, func, opts);
      else
        c[func](opts);
    })
  }
}

You can use the SuperForm npm package to do that for you.

like image 31
Pian0_M4n Avatar answered Sep 19 '22 14:09

Pian0_M4n