AppDividend
Latest Code Tutorials

Angular Checkbox Example | Angular 9 Checkbox Tutorial

1

Angular checkbox is a regular checkbox that can be seen as a square box that is ticked (checked) when activated. 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.

Angular checkbox example

A typical UI pattern for application is to have the collection of elements where the user must select one too many of the given items.

We typically would handle this scenario with a checkbox list.

In this post, 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 submit the form, and we get the array of selected values.

Step 1: Install Angular 9 project

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

If you are unfamiliar with Angular, then check out the Angular 9 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, in the checkbox, we will display these name values from the above array.

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

Step 3: Define the HTML view for 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 also 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 change() event will fire, and then cartoon name and checked values are passed to that onChange() function that is 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 are running 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.

Now, 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, first, we have 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 the value and validation status of an individual form control.

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

Then defined a constructor and created 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, then we are pushing the checked values to the FormArray and removing the values if the user unchecks the checkbox options.

Inside the submit() function, we are getting 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 are logged, which means we have successfully got the checked the values inside the array.

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

Finally, Angular checkbox example tutorial is over.

See also

Angular CRUD

Angular forms

Angular file upload

Angular HttpClient

Angular Observables

1 Comment
  1. Amit Parmar says

    Thanks for explaining the things. There are many-things which clears my doubt .

Leave A Reply

Your email address will not be published.

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