如何在Angular中将对象数组映射到formarray

时间:2019-06-01 00:00:43

标签: angular angular-forms formarray

将数据数组映射到复选框数组的正确方法是什么? 我尝试了下面的代码,但是它不起作用...目标是从httpclient获取信息并将其映射到可以的数据数组,但无法将数据数组正确映射为表单数组...

data = [
      { id: false, name: "Ovo" },
      { id: false, name: "Ono" },
      { id: false, name: "Levo" },
      { id: false, name: "Desno" }
    ];
this.postForm = this.fb.group({
      osnovne: this.fb.group({
        sekcija: ["market", Validators.required],
        kategorija: "",
        cena: [""],
        dogovor: false,
        opis: ""
      }),
      detaljne: this.fb.group({
        select: this.fb.array([]),
        checkboxes: this.fb.array([])
      }),

      imagePath: this.fb.group({
        data: ""
      })
    });

模板

<form [formGroup]="postForm">
  <div formGroupName="detaljne">
    <div
      formArrayName="checkboxes"
      *ngFor="let data of data; let i = index"
    >
      <input [id]="data.id" type="checkbox" [formControl]="checkboxes[i]" />
      <label [for]="data.id">
        {{ data.name }}</label
      >
    </div>
  </div>
</form>

1 个答案:

答案 0 :(得分:1)

您只需要在索引的复选框数组库中设置formControtName

这是我如何设置控件数据 updateDataControls

  ngOnInit() {
    const cData: IControls<boolean>[] = [
      { value: false, name: "Ovo" },
      { value: true, name: "Ono" },
      { value: false, name: "Levo" },
      { value: true, name: "Desno" }
    ]
    this.updateDataControls(cData)

  }

  updateDataControls(controls: IControls<any>[]) {
    this.data = controls;
    const controlsForm = this.form.get('controls').get('checkboxes') as FormArray;
    for (const c of controls) {
      controlsForm.push(this.fb.control(c.value))
    }
  }

模板

<div [formGroup]="form">
    <div formGroupName="controls">
        <div formArrayName="checkboxes">
            <div *ngFor="let c of data;let index = index">
                <label>{{c.name}}</label>
        <input type="checkbox" [formControlName]="index" >
      </div>
     </div>
  </div>
</div>

stackblitz demo 上查看完整的示例