1
  form: ControlGroup
  childForm1: ControlGroup
  childForm2: ControlGroup
  childForm3: ControlGroup

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      name: [''],
      childForm1: fb.group({
        child1: [''],
        child2: ['']
      }),
      childForm2: fb.group({
        child3: [''],
        child4: ['']
      }),
      childForm3: fb.group({
        child5: [''],
        child6: ['']
      })
    });
  }

I can get name by two ways:

  console.log(this.form.find('name'));
  console.log(this.form.controls['name']);

But I cannot use similar way to get child1.

I know a way:

for (name in this.childForm1.controls) {
    if (name === "child1") {
        console.log(this.childForm1.controls[name]);
    }
}

But this still uses childForm1 in the code.

Is it possible using only form and child1 to get it? Thanks

Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267

2 Answers2

0

You could try this to get the child controls of child1:

var child1Controls = this.form.controls.childForm1.controls;

As a matter of fact, the group method returns a ControlGroup element:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0

I realized this is nested objects problem. So I created a simplified question, and got an answer from @dave.

But in this case you cannot use typeof to decide whether is is Control or ControlGroup, I got answer from @thierry-templier. So you need change a little bit of the code.

So he final working version:

getControl(controlName:string, controls:Object): AbstractControl {
    for (let i in controls) {
        if (controls.hasOwnProperty(i)) {
            if (i === controlName) {
                return controls[i];
            } else if (controls[i] instanceof ControlGroup) {
                let control:AbstractControl = this.getControl(controlName, controls[i].controls);
                if (typeof(control) !== "undefined") {
                    return control;
                }
            }
        }
    }
}

To use it

let control = this.getControl(this.controlName, this.form.controls);
Community
  • 1
  • 1
Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267