Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive forms: mark dirty all controls in form group

I have Angular 6 app with form. Here is an examle

export class ExampleComponent implements OnInit {
    form: FormGroup;

    constructor(private fb: FormBuilder) { }

    ngOnInit() {
        this.form = new FormGroup({
            first: new FormControl(),
            last: new FormControl()
        });

        this.markControlsAsDirty(this.form);
    }

    markControlsAsDirty(form: FormGroup) {
        this.form.get('first').markAsDirty();
        this.form.get('last').markAsDirty();
    }
}

I don't want to get a single control and mark every field. Can I mark all controls in form group as dirty?

UPDATE I've been added stackblitz example to show that two previous answers were wrong

like image 743
hofshteyn Avatar asked Mar 01 '19 10:03

hofshteyn


People also ask

Does Patchvalue set dirty?

Bookmark this question.

What is form dirty in angular?

When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"

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.


1 Answers

If you have a complicated form structure, you can segregate the code to mark FormGroup, FormArray or FormControl as dirty. See the example here : Mark Form as dirty

markDirty() {
this.markGroupDirty(this.form);
console.log('FORM:', this.form);}
markGroupDirty(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(key => {
  switch (formGroup.get(key).constructor.name) {
    case "FormGroup":
      this.markGroupDirty(formGroup.get(key) as FormGroup);
      break;
    case "FormArray":
      this.markArrayDirty(formGroup.get(key) as FormArray);
      break;
    case "FormControl":
      this.markControlDirty(formGroup.get(key) as FormControl);
      break;
  }
});
}
markArrayDirty(formArray: FormArray) {
formArray.controls.forEach(control => {
  switch (control.constructor.name) {
    case "FormGroup":
      this.markGroupDirty(control as FormGroup);
      break;
    case "FormArray":
      this.markArrayDirty(control as FormArray);
      break;
    case "FormControl":
      this.markControlDirty(control as FormControl);
      break;
  }
 });
}
markControlDirty(formControl: FormControl) {
     formControl.markAsDirty();
}
like image 160
Sachin Gupta Avatar answered Sep 17 '22 22:09

Sachin Gupta