首页 > 解决方案 > 为什么输入没有从 FormArray 显示

问题描述

看看这段代码:

https://stackblitz.com/edit/angular-usshu2?embed=1&file=src%2Fapp%2Fapp.component.ts&fbclid=IwAR171rBtZZsG3a29coIw9jnZK4rBTRj4Tn5mEFSCwRd4uosD5KaUwobE9Rk

我从字面上复制粘贴了代码,它返回的唯一内容是保存按钮。

我在控制台中收到此错误:-

错误错误:找不到类型为“对象”的不同支持对象“[对象对象]”。NgFor 仅支持绑定到 Iterables,例如 Arrays。

app.component.ts:

 constructor(private _formBuilder: FormBuilder) {}


ngOnInit(){

this.loanProductForm = this._formBuilder.group({
  products: this._formBuilder.array([this.addProductFormGroup()])
});
 
})
}

addProductFormGroup(): FormGroup {
return this._formBuilder.group({
 productId: ["", Validators.required],
   price: ["", Validators.required],
  
});



}

addProductButtonClick(): void {
(<FormArray>this.loanProductForm.get("products")).push(
  this.addProductFormGroup()
);


}
 getControls(combo){
return combo.get('products').controls;
}

 onSubmit() {
console.log(this.loanProductForm.value)

 }

组件.html:

<form class="form-horizontal" [formGroup]="loanProductForm" (ngSubmit)="onSubmit()">
    <table>
        <tr formArrayName="products" *ngFor="let item of loanProductForm.controls; let i = index">
            <div [formGroupName]="i">
                <td>
                    <input type="text" class="form-control" [id]="'productId' + i" placeholder="productId"  formControlName="productId">
                    <div *ngIf="item.get('productId').errors.required &&
                    item.get('productId').touched">
                  ProductId is required
          </div>
                </td>
                <td>
                    <input type="text" class="form-control" [id]="'price' + i" placeholder="price"  formControlName="price">
                    <div *ngIf="item.get('price').errors.required &&
                    item.get('price').touched">
                  price is required
          </div>
                </td>
                <!-- <td>
                    <input type="text" class="form-control" [id]="'loanTermId' + i" placeholder="loanTermId"  formControlName="loanTermId">
       </td>
                <td>
                    <input type="text" class="form-control" [id]="'quantity' + i" placeholder="quantity"  formControlName="quantity">
       </td> -->
                <td>
                    <button type="button" (click)="addProductButtonClick()" >Add</button>
                </td>
            </div>
        </tr>
    </table>
    <input type="submit" value="Save"/>
</form>

标签: angularformarray

解决方案


FormGroup 在“products”属性中有数组,因此您必须更改loanProductForm.controlsloanProductForm.get('products').controls获取 formArray

IE

<tr formArrayName="products" *ngFor="let item of loanProductForm.controls; let i = index">

<tr formArrayName="products" *ngFor="let item of loanProductForm.get('products').controls; let i = index">

推荐阅读