Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Iterate over reactive form controls

Tags:

angular

People also ask

What is FormArray in angular?

A FormArray aggregates the values of each child FormControl into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a FormArray is invalid, the entire array becomes invalid.


Found out that Object.keys can handle this..

    Object.keys(this.form.controls).forEach(key => {
      this.form.get(key).markAsDirty();
    });

For Angular 8+, use the following (based on Michelangelo answer):

    Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsDirty();
    });

For what it's worth, there's another way to do this without having to use Object.keys(...) magic:

for (const field in this.form.controls) { // 'field' is a string

  const control = this.form.get(field); // 'control' is a FormControl  

}

The accepted answer is correct for a flat form structure, but does not completely answer the original question. A web page may require nested FormGroups and FormArrays, and we must account for this to create a robust solution.

public markControlsDirty(group: FormGroup | FormArray): void {
    Object.keys(group.controls).forEach((key: string) => {
        const abstractControl = group.controls[key];

        if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
            this.markControlsDirty(abstractControl);
        } else {
            abstractControl.markAsDirty();
        }
    });
}

Seems that get function is not working anymore for retrieving specific values in your form in Angular 8, so this is how I solved it based on the answer of @Liviu Ilea.

for (const field in this.myForm.controls) { // 'field' is a string
  console.log(this.myForm.controls[field].value);
}

Using @Marcos answer I created a function that can be called passing a formGroup as parameter and it marks every formGroup children controls to dirty, just to make it usable from more places around the code putting it inside a service, for example.

public touchAllFormFields(formGroup: FormGroup): void {
    Object.keys(formGroup.controls).forEach((key) => {
        formGroup.get(key).markAsDirty();
    });
}

hope it helps ;)


    Object.keys( this.registerForm.controls).forEach(key => {
       this.registerForm.controls[key].markAsDirty();
    });