Thuan Tran
Thuan Tran

Reputation: 329

Access value of nested formgroup Angular

I have a nested FormGroup as below:

formData = new FormGroup({
      item0: this.createForm(),
      item1: this.createForm(),
      item2: this.createForm(),
      item3: this.createForm()
    });

each item is a formgroup with 3 properties created by the createForm function:

createForm() {
    return new FormGroup({
      title: new FormControl(undefined, Validators.required),
      imgData: new FormControl(undefined, Validators.required),
      description: new FormControl(undefined, Validators.required)
    });
  }

now I need to access the value inside imgData of, for example, item2, so I tried:

formData.controls['item2'].controls['imgData'].value

but it has an error: Property 'controls ' does not exist on type 'AbstractControl'.

when I try using .get('imgData') it works just fine, though.

Is there a way to achieve this without get and just use with controls?

Upvotes: 1

Views: 941

Answers (1)

bryan60
bryan60

Reputation: 29335

a couple of ways, you can just get the overall value:

formData.value.item2.imgData

or cast as FormGroup...

(<FormGroup>formData.controls['item2']).controls['imgData'].value;

controls and get() both return AbstractControls which may be a control or group or array. you need to tell angular which it is, as controls don't have controls of their own.

Upvotes: 1

Related Questions