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

  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 {
      .subscribe(fruits => {
        this.fruitsForm ={
          name: "Joe Bloggs",
          fruits: this.fb.array( =>


<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" />
    <br />
    <div>{{fruitsForm.value | json}}</div>

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;

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

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