Search code examples
angularangular-formsformarray

How to map object array to formarray in Angular


What is the proper way to map data array to checkboxes form array? I tried code bellow but it doesn't work...Goal is to get informations from httpclient and map it to data array that's ok, but cannot map data array to form array correctly...

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: ""
      })
    });

Template

<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>

Solution

  • you just need to set the formControtName in the checkboxes array base of the index

    this how I set the controls data 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))
        }
      }
    

    template

    <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>
    

    check the complete example at 👉 stackblitz demo 🔥🔥