查看下面的代码:
https://stackblitz.com/edit/angular-usshu2?embed=1&文件= src % 2 fapp % 2 fapp.component.ts& fbclid = IwAR171rBtZZsG3a29coIw9jnZK4rBTRj4Tn5mEFSCwRd4uosD5KaUwobE9Rk
我复制粘贴了代码,它唯一返回的是保存按钮。
我在控制台得到这个错误:-
ERROR错误:无法找到类型为object的不同支持对象'[object object]'。NgFor只支持绑定到数组之类的Iterables。
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)
}
component.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>
FormGroup在"products"属性,因此你必须将loanProductForm.controls
更改为loanProductForm.get('products').controls
以获得formArray
。
<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">