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!
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 { }
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.
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.
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.
FormBuilder: It creates the AbstractControl from a user-specified configuration.
FormGroup: It tracks the value and validity state of a group of FormControl instances
FormArray: Tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances
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.
name
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.
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