angular - 为什么输入没有从 FormArray 显示
问题描述
看看这段代码:
我从字面上复制粘贴了代码,它返回的唯一内容是保存按钮。
我在控制台中收到此错误:-
错误错误:找不到类型为“对象”的不同支持对象“[对象对象]”。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>
解决方案
FormGroup 在“products”属性中有数组,因此您必须更改loanProductForm.controls
为loanProductForm.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">
推荐阅读
- c - Scanf 使 do_while 循环卡住
- java - Java - [SQLITE_BUSY] 数据库文件被锁定(数据库被锁定)
- html - 删除gridview上的重复行
- php - 如何摆脱未定义的偏移量
- matlab - 交换矩阵的片段 Matlab
- android - 如何使来自互联网的图像响应 Android 布局?
- c# - 获取 HTTP 错误 500.30 - PhysicalFileProvider
- python - 在 Jupyter Notebook 上使用 Julia 出现内核错误
- logging - 如何在 F# 中使用 ZeroLog?
- c - 如何从 C 中的 SSL/ssl_st 结构中获取远程/对等 IP 地址?