Angular 12 Checkbox Example: Add Multi Checkboxes Validation

This is a comprehensive Angular 12 Checkbox tutorial; this tutorial walks you through on selecting, unselect, and validating multiple checkboxes in angular using angular reactive forms.

Handling angular checkbox and multi checkboxes is effortless; you can do it without being solicitous.

Angular 12 Checkboxes Example

A checkbox is a user interface element used to select one or multiple values, among other values.

You can select multiple Checkbox options at once and simultaneously validate the checkbox in Angular 12.

Angular offers Reactive Forms and Template Driven forms to deal with the user-entered data; you can use any approaches to work with checkboxes in angular.

Getting Started

Execute the following command to create a new angular project; avoid this step if you have already done this.

ng new angular-checkboxes-tutorial

Move to the project root:

cd angular-checkboxes-tutorial

Import ReactiveFormsModule and FormsModule in the app.module.ts file.

import { AppComponent } from './app.component';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';

@NgModule({
  declarations: [...],
  imports: [
    ReactiveFormsModule,
    FormsModule
  ],
  providers: [...],
  bootstrap: [...]
})

Creating Checkboxes in Angular

Next, the foremost step is to create checkboxes using Angular HTML attributes. Place the code in app.component.html.

<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
    <input type="submit" value="Submit">
</form>

Start importing Reactive Forms module in app.component.ts file.

import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

Adding Checkbox Object

There are two ways to add a checkbox object in an angular one; you can define it statically. Another way is you can make the Http GET request and fetch the data from the server.

MoviesData: Array<any> = [
    { name: 'avenger', value: 'Avenger' },
    { name: 'inception', value: 'Inception' },
    { name: 'parasite', value: 'Parasite' },
    { name: 'joker', value: 'Joker' },
    { name: 'shoplifters', value: 'Shoplifters' }
];

Open the app.component.ts file, set the FormGroup API in AppComponent class, afterwards inject the FormBuilder service within the angular constructor method.

A form object can be initialized using FormBuilder API.

export class AppComponent {
  form: FormGroup;
  
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      isArray: this.fb.array([], [Validators.required])
    })
  }

The isArray is made of using the FormArray service, its a form control and in this tutorial help in working with multiple checkboxes values.

Multiple Checkboxes in Angular

The following code helps you handle multiple checkboxes in Angular.

onCbChange(e) {
    const isArray: FormArray = this.form.get('isArray') as FormArray;

    if (e.target.checked) {
      isArray.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      isArray.controls.forEach((item: FormControl) => {
        if (item.value == e.target.value) {
          isArray.removeAt(i);
          return;
        }
        i++;
      });
    }
 }

Checkboxes Validation in Angular

In this step we are learning how to validate angular checkboxes. Also, here we will display the final code of this tutorial.

Code goes in app.component.ts file.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  form: FormGroup;
  MoviesData: Array<any> = [
    { name: 'avenger', value: 'Avenger' },
    { name: 'inception', value: 'Inception' },
    { name: 'parasite', value: 'Parasite' },
    { name: 'joker', value: 'Joker' },
    { name: 'shoplifters', value: 'Shoplifters' }
  ];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      isArray: this.fb.array([], [Validators.required])
    })
  }

  onCbChange(e) {
    const isArray: FormArray = this.form.get('isArray') as FormArray;

    if (e.target.checked) {
      isArray.push(new FormControl(e.target.value));
    } else {
      let i: number = 0;
      isArray.controls.forEach((item: FormControl) => {
        if (item.value == e.target.value) {
          isArray.removeAt(i);
          return;
        }
        i++;
      });
    }
  }

  onSubmit() {
    console.log(this.form.value)
  }
}

Display Validation Error

Add the code in app.component.html file.

<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>

  <div *ngFor="let item of MoviesData; let i=index">
    <label>
      <input type="checkbox" [value]="item.value" (change)="onCbChange($event)" />
      {{item.name}}
    </label>
  </div>

  <p class="error" *ngIf="this.form.controls['isArray'].errors?.required">
    Checkbox value is required.
  </p>

  <input type="submit" value="Submit">
</form>

Summary

You can run the ng serve --open command from your terminal to see your angular multiple checkboxes application’s final status. Do make sure validation is applied to the checkboxes properly or not.