【发布时间】:2021-01-21 07:22:39
【问题描述】:
我有一个包含数组值的表单。值以完美的形式显示,但在保存值时它并没有绑定整个数组值;而不是仅绑定最后更改的值。
另外,formControlName="id" 属性值没有绑定到 formArray 对象中。
App.component.ts
initializRecords(data?: any) {
this.dataForm = this.formBuilder.group({
dataCollection: this.formBuilder.group({
id: new FormControl(),
sizeId: new FormControl(),
sizes: this.formBuilder.group({
qty: new FormControl([])
})
})
});
}
App.component.html
<form [formGroup]="dataForm">
<div class="container">
<div class="row">
<div class="col">
<button mat-raised-button color="primary" (click)="saveRecords()">Save</button>
</div>
</div>
<div formArrayName="dataCollection">
<div class="row" *ngFor="let element of data; let first = first">
<div *ngIf="!first">----------</div>
<ng-container *ngFor="let subElement of element.sizes">
<div class="col">
<mat-form-field class="">
<input matInput type="text" formControlName="id" value={{element.value}} readonly>
</mat-form-field>
<mat-form-field class="">
<input matInput type="text" value={{subElement.subValue}} readonly>
<input type="hidden" formControlName="sizeId">
</mat-form-field>
<div formGroupName="sizes">
<mat-form-field class="">
<input matInput type="text" formControlName="qty" value={{subElement.qty}}>
</mat-form-field>
</div>
</div>
</ng-container>
</div>
</div>
</div>
</form>
=== 更新 ===
单击保存事件时,我希望最终 JSON 结构如下所示,因为值按行显示。
{
"data": [
{ "id": 1, "sizeId": 1, "qty": 10 },
{ "id": 1, "sizeId": 2, "qty": 1 },
{ "id": 1, "sizeId": 3, "qty": 1 },
{ "id": 2, "sizeId": 1, "qty": 50 },
{ "id": 2, "sizeId": 2, "qty": 60 },
{ "id": 2, "sizeId": 3, "qty": 70 },
]}
【问题讨论】:
标签: angular angular-reactive-forms formarray