How do I access value of ItemName in HTML. It says undefined when I try {{invoiceForm.controls[i].items.controls.itemName.value | json}}
in below code.
<form [formGroup]="invoiceForm">
<div formArrayName="items" *ngFor="let item of items.controls; let i=index;">
<div [formGroupName]="i">
<input type="text" formControlName="itemName">
<input type="number" formControlName="itemQty">
<input type="number" formControlName="itemPrice">
</div>
Item name: {{invoiceForm.controls[i].items.controls.itemName.value | json}}
</div>
</form>
You were almost there...
instead of:
{{invoiceForm.controls[i].items.controls.itemName.value | json}}
You should write:
{{invoiceForm.controls['items'].controls[i].controls.itemName.value | json}}
StackBlitz example
In order to tell the exact path to go, you could have just print the form value with console.log(this.invoiceForm)
on ngOnInit
and then you could have seen that the 'item'
is a direct key of 'controls'
, your only mistake was to refer invoiceForm.controls[0]
which is wrong.
Here is a little extra for achieving the same outcome form ts file (hard coded to the first item):
console.log(this.invoiceForm);
const itemControls = <FormArray>this.invoiceForm.controls['items'];
const itemFormGroup = <FormGroup>itemControls.controls[0];
console.log(itemFormGroup.controls["itemName"].value);