【问题标题】:Angular 6: How to bind the formArray value on save event?Angular 6:如何在保存事件上绑定 formArray 值?
【发布时间】:2021-01-21 07:22:39
【问题描述】:

我有一个包含数组值的表单。值以完美的形式显示,但在保存值时它并没有绑定整个数组值;而不是仅绑定最后更改的值。

另外,formControlName="id" 属性值没有绑定到 formArray 对象中。

StackBlitz working demo.

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


    【解决方案1】:

    我觉得你对表单的使用不是很好。

    您有两种不同类型的数据,一种是“Lorium”,另一种是“Ipsum”。我认为您应该首先在 dataCollection 上定义一个数组,在其中创建 2 个不同的 FormGroup

    然后在每个FormGroup 中,您将拥有一个包含所有子元素的数组。

    我不确定您需要什么并尝试对您的程序进行处理,但这样一来,您就可以根据需要存储所有数量。

    我以这种思维方式与您分享一个工作example。如果你认为我误解了什么,请告诉我。

    此外,您可以在每个 FormGroup 上添加您需要的任何 FormControl,以使表单与您的 json 数据相匹配。

    最后,如果您想适应所需的 JSON,只需遍历您的元素以将它们添加到对象中。

    【讨论】:

    • 是的,它的工作方式与我的预期要求几乎相似。但最后我需要对同一个对象集合数组的响应。我已经更新了关于响应中所需的样本 json 集合的问题,您能查看一下吗?
    • @AJT81 我已经编辑了stackblitz,检查它是否适合你:)
    • 呼!!!似乎工作正常。让我融入我的实际项目。非常感谢您的时间和努力。干杯!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多