在 HTML 中以响应式形式从 formArray 访问 formControl 的值

use*_*891 6 html javascript angular angular-reactive-forms

如何访问 HTML 中 ItemName 的值。当我尝试{{invoiceForm.controls[i].items.controls.itemName.value | json}}下面的代码时它说未定义。

<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>
Run Code Online (Sandbox Code Playgroud)

Sha*_*ani 5

You were almost there...

instead of:

{{invoiceForm.controls[i].items.controls.itemName.value | json}}
Run Code Online (Sandbox Code Playgroud)

You should write:

{{invoiceForm.controls['items'].controls[i].controls.itemName.value | json}}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

  • 标识符“控件”未定义。“AbstractControl”不包含这样的成员。这是错误。 (2认同)