admin管理员组

文章数量:1279147

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>

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>
Share Improve this question edited May 6, 2020 at 9:06 Shahar Shokrani 8,76210 gold badges57 silver badges102 bronze badges asked May 4, 2020 at 21:00 SurajSuraj 5863 gold badges11 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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 oute 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);

instead of {{invoiceForm.controls[i].items.controls.itemName.value | json}}

Try this in html :

{{getFormControlItem()[i].controls['dateofStay'].value}}

Component ts code :

getFormControlItem()
{
return ((this.invoiceForm.controls['items'] as FormArray).controls as FormGroup[])
}

this will not throw this error : Property 'controls' does not exist on type 'AbstractControl'.

This workerd in my case .

本文标签: javascriptAccess value of formControl from formArray in reactive form in HTMLStack Overflow