Angular 8 Checkbox : Angular 8 Checkbox Tutorial with Example

Angular 8 Checkbox : Angular 8 Checkbox Tutorial with Example

A checkbox is also known as the tick-box and it is a Graphical User Interface widget that allows a user to choose one or many possible options. In this article, we will build a checkbox list with Angular but create it dynamically from a list.

If you have been creating any type of applications till now, you are already aware of the huge significance that a checkbox holds. Not only does it makes the input of data easier to any platform, but it also facilitates the quick sorting of data as it often comes packaged with the list feature. A checkbox is also known as the tick-box and it is a Graphical User Interface widget that allows a user to choose one or many possible options. In this article, we will build a checkbox list with Angular but create it dynamically from a list.

Let’s get started!

Install Angular 8 project

If you do not know how to update angular cli, then check out the update angular 8 cli tutorial If you are unfamiliar with Angular, then check out the Angular 8 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.

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 { }

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.

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.

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.

This is image title

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.

angular angular8

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular. Angular is a Typesc

Angular Sass: How To Use Sass In Angular 9 Tutorial

Sass in Angular is an extension of CSS that allows you to use things like variables, nested rules, inline imports. Angular supports Sass, CSS, and Less.

Angular 9/8 Authentication Form: Angular FormBuilder, FormGroup

Throughout this step by step article, we’ll be learning about how to create an Angular 9 web application with an authentication form for…

How to Upgrade Angular 8 To Angular 9

Angular is currently the most popular JavaScript framework and is used by several expert developers when developing single-page applications or powerful web apps. It has become quite crucial for the developers of Angular to add more features to the framework and fix the bugs . Let's learn how to upgrade Angular 8 to Angular 9 using CLI.