Angular Checkbox: How to Use Checkbox in Angular 13

A typical UI pattern for an application is a collection of elements where the user must select one too many given items. We typically would handle this scenario with a checkbox list.

Angular checkbox

The angular checkbox is a regular checkbox that can be seen as a square box that is ticked (checked) when activated. We will build a checkbox list with Angular but create it dynamically from a list. Then the user selects the checkbox and pushes it into one array and then submits the form, and we get the array of selected values.

HTML checkboxes are used to let a user select one or more options for a limited number of choices. In HTML, the <input type=”checkbox”> defines a checkbox.

Step 1: Install Angular 13 project

If you do not know how to update angular cli, check out the update Angular cli tutorial.

If you are unfamiliar with Angular, then check out the Angular tutorial.

Now, create a brand new angular project using the following command.

ng new ang

Now, go inside the folder and open the project in Visual Studio Code.

Okay, the next step is to import FormsModule and ReactiveFormsModule inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 2: Define data to show checkbox

Inside the app.component.ts file, we will define the following data.

// app.component.ts

...
cartoonsData: Cartoon[] = [
    { id: 0, name: 'Tom and Jerry' },
    { id: 1, name: 'Rick and Morty' },
    { id: 2, name: 'Ben 10' },
    { id: 3, name: 'Batman: The Animated Series' }
  ];
...

So, we will display these name values from the above array in the checkbox.

The user then selects their favorite cartoon and submits the form, and then in the submit() function, we will get those selected values.

Step 3: Define the HTML view for the checkbox

Write the following code inside the app.component.html file.

<!-- app.component.html -->

<div style="margin-top: 30px">
<form [formGroup]="form" (ngSubmit)="submit()">
  <div *ngFor="let cartoon of cartoonsData">
    <input type="checkbox" (change)="onChange(cartoon.name, $event.target.checked)" />
    {{ cartoon.name }}
  </div>
  <button>submit</button>
</form>
</div>

In the above code, we have attached a formGroup directive to form and use the ngSubmit event.

So, when the user clicks on the submit button, the ngSubmit() event fires, and it calls the submit() function.

Then we have used the ngFor directive to display the dynamic checkbox list with the onChange() event.

If the user clicks the checkbox, then the change() event will fire, and then cartoon name and checked values are passed to that onChange() function associated with that event.

We will define the onChange() function inside the app.component.ts file.

Don’t save the file and go to the browser if you run the project because you will get the error.

Now, let’s head to the last step.

Step 4: Define onChange() and submit() function

Okay, so now we have our app.component.html and app.module.ts file complete.

We need to define two main functions to track the checkbox values and get those checked values.

Write the following code inside the app.component.ts file.

// app.component.ts

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

export interface Cartoon {
  id: number;
  name: string;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  form: FormGroup;
  cartoonsData: Cartoon[] = [
    { id: 0, name: 'Tom and Jerry' },
    { id: 1, name: 'Rick and Morty' },
    { id: 2, name: 'Ben 10' },
    { id: 3, name: 'Batman: The Animated Series' }
  ];

  constructor(private fb: FormBuilder) { }

  onChange(name: string, isChecked: boolean) {
    const cartoons = (this.form.controls.name as FormArray);

    if (isChecked) {
      cartoons.push(new FormControl(name));
    } else {
      const index = cartoons.controls.findIndex(x => x.value === name);
      cartoons.removeAt(index);
    }
  }

  ngOnInit() {
    this.form = this.fb.group({
      name: this.fb.array([])
    });
  }

  submit() {
    console.log(this.form.value.name);
  }
}

In the above code, we first imported four forms modules from forms packages.

  1. FormBuilder: It creates the AbstractControl from a user-specified configuration.
  2. FormGroup: It tracks the value and validity state of a group of FormControl instances
  3. FormArray: Tracks the value and validity state of an array of FormControl, FormGroup, or FormArray instances
  4. FormControl: It tracks an individual form control’s value and validation status.

Then we have defined the interface Cartoon, which is the type of data of the checkbox.

Then defined a constructor and created a FormBuilder instance.

In the next step, we have defined the onChange() function, which takes two parameters.

  1. name
  2. isChecked

If the particular checkbox values are checked, we push the checked values to the FormArray and remove the values if the user unchecks the checkbox options.

Inside the submit() function, we get the checked values array and log it in the console.

Finally, see the output.

Angular Checkbox Example

You can see in the console that an array of two values is logged, which means we have successfully checked the values inside the array.

Now, we can send that array to the server and save it inside the database.

That’s it for the angular checkbox example.

See also

Angular CRUD

Angular forms

Angular file upload

Angular HttpClient

Angular Observables

2 thoughts on “Angular Checkbox: How to Use Checkbox in Angular 13”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.