this.InvoiceForm=this.fb.group({
InvoiceNumber:[''],
EntryDate:[''],
InvoiceItem:this.fb.array([this.AddItemFormGroup()])
})
AddItemFormGroup()
{
return this.fb.group({
ItemName:[''],
ItemType:['']
})
Save()
{
console.log(this.InvoiceForm.value);
console.log(this.InvoiceForm.InvoiceItem[0].ItemName);
}
when I log the values it shows but when I log the value of specific row of nested form array it give error: ERROR TypeError: Cannot read properties of undefined (reading 'ItemName')
CodePudding user response:
console.log((this.InvoiceForm.get('InvoiceItem') as FormArray).at(0).get('ItemName').value)
since InvoiceForm
is a FormGroup
object, you cannot directly access the controls by indexing the key. You either have to do it as @Eugene mentioned in the comment using: this.InvoiceForm.controls.InvoiceItem
or by using get
like this: this.InvoiceForm.get('InvoiceItem')
which will return the InvoiceItem
control.
Now if you wanted to access the value of the control you'd have to do this this.InvoiceForm.get('InvoiceItem').value
, but since InvoiceItem
in our case is not a simple FormControl
but a FormArray
we can only use the properties available to FormArray
And since its a FormArray
we can use the .at(index)
method to get the specific control or value. We use as FormArray
since typescript
assumes the type is a generic FormControl
and not a FormArray