4

I am using angular 5 with formgorup and wish to iterate the controls, in order to create a dynamic component based on a form, the forms fields are given by an external data service (database etc.)

It is declares as follows

check = new FormGroup({
    firstName : new FormControl(true),
    lastName : new FormControl(false)
  });

I found this explaining how to iterate the controls but It does not work. I try to use:

for(let item of this.check.controls){}

and get this is the chrome debug:

Cannot read property 'length' of undefined

I can't access this.check.controls.keys or keys()

How can I iterate the keys?

Thanks

thebeancounter
  • 4,261
  • 8
  • 61
  • 109

4 Answers4

9

try use Object.keys method to get object keys

Object.keys(this.check.controls); // => ["firstName", "lastName"]

this.check.controls is object key/value paire structure if you want to get the keys of the object {key1:value,key2:value} you can use Object.keys method that return an array contains keys ['key1','key2']

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
3

This Form Returning the Object of value not array of value

check = new FormGroup({
        firstName : new FormControl(true),
        lastName : new FormControl(false)
      });

If you want to get keys then you have to use The Object.keys() method returns an array of a given object's property names, in the same order as we get with a normal loop

KeyArray= Object.keys(this.check.controls)// ["firstName", "lastName"]

Example:https://stackblitz.com/edit/angular-stszta

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
1

iterate over an object:

for(let item in this.check.controls){
    console.log(this.check.controls[item])
}
Fateme Fazli
  • 11,582
  • 2
  • 31
  • 48
0

this function works pretty good for me

public static ResetForm(form: FormGroup, config = {}) {
    const controls: string[] = Object.keys(form.controls);

    controls.forEach(key => {
      if (config[key] && config[key]["default"])
        form.get(key).setValue(config[key]["default"]);
      else form.get(key).setValue("");
      form.get(key).setErrors(null);
      form.get(key).markAsTouched();
    });
  }

if you want to set default value other then empty string, use config object as follow

ResetForm(this.form, {
      categories: {
        default: []
      }
    });