how do you set the checked boxes on the database as an angular reactive form?

Here is a working example of populating a list of checkboxes in a reactive form.

import { Component, OnInit } from "@angular/core";
import { FormArray, FormBuilder, FormGroup } from "@angular/forms";
import { take } from "rxjs/operators";
import { DataService } from "./data.service";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  public fruitsForm: FormGroup;

  get fruitsArray() : FormArray {
    return this.fruitsForm.get('fruits') as FormArray
  } 

  constructor(private dataService: DataService, private fb: FormBuilder) {}

  ngOnInit(): void {
    this.dataService
      .getFruits()
      .pipe(take(1))
      .subscribe(fruits => {
        this.fruitsForm = this.fb.group({
          name: "Joe Bloggs",
          fruits: this.fb.array(fruits.map(f => this.fb.group(f)))
        });
      });
  }
}

HTML

<ng-container *ngIf="fruitsForm">
    <form [formGroup]="fruitsForm">
        <input name="name" formControlName="name" />
        <div formArrayName="fruits">
            <div *ngFor="let fruit of fruitsArray.controls; let i = index" [formGroupName]="i">
                <input type="checkbox" formControlName="selected" />
                <label>{{fruit.value.name}}</label>
            </div>
        </div>
    </form>
    <br />
    <div>{{fruitsForm.value | json}}</div>
</ng-container>

We’ve simulated a fetch from the database using a service and the RxJS delay operator.

import { Injectable } from "@angular/core";
import { Observable, of } from "rxjs";
import { delay } from "rxjs/operators";

interface Fruit {
  id: number;
  name: string;
  selected: boolean;
}

@Injectable()
export class DataService {
  constructor() {}

  public getFruits(): Observable<Fruit[]> {
    return of([
      {
        id: 1,
        name: "Apple",
        selected: true
      },
      {
        id: 2,
        name: "Pear",
        selected: false
      },
      {
        id: 3,
        name: "Orange",
        selected: false
      }
    ]).pipe(delay(250));
  }
}

We use the FormBuilder service to build our form.

We bundle our controls into a FormGroup called fruitsForm.

In our FormGroup, fruits is a FormArray, allowing for many inputs.

Each Fruit object is mapped to a new FormGroup, and each property in our Fruit object will be converted into a FormControl.

The fruitsArray getter is to make it easier to access our form property.

To connect our template to the FormArray, we use the formArrayName directive.

The formGroupName directive uses the index find the correct FormGroup in our fruits FormGroup. To connect our checkbox to the selected control, we use the formControlName directive.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top