How to Use Checkbox in Angular [Step-by-Step Guide]

The angular checkbox is a regular checkbox that can be seen as a square box ticked (checked) when activated.  HTML checkboxes let a user select one or more options for a limited number of choices. The <input type=”checkbox”> defines a checkbox in HTML.

Here is a step-by-step guide to use the checkbox in Angular.

Step 1: Install the Angular project

Create a brand new angular project using the following command.

ng new ang

Go inside the folder and open the project in Visual Studio Code.

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

Inside the app.component.ts file, 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' }
  ];
...

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>

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

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

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.

That’s it!

2 thoughts on “How to Use Checkbox in Angular [Step-by-Step Guide]”

Leave a Comment

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