Angular Checkbox tutorials with latest examples
This tutorial explains checkbox tutorials with examples for following
- two-way binding example
- Dynamic Checkbox list
- Get the checkbox value in Angular
- How to find checkbox is checked or not
prerequisite
First, Create an angular application using Angular CLI - ng commands,
Once, Application is created, dependencies are installed, and You can start importing FormsModule
Import FormsModule
and ReactiveFormsModule
in Application Module, These modules are required to have input form binding works in the Angular application.
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
import { HelloComponent } from "./hello.component";
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Angular checkbox two-way binding example
Two-way binding in Angular provides passing data from HTML to typescript components and vice versa.
This can be achieved with simple ngModel syntax - [()]
<input [(ngModel)]="isAccepted" type="checkbox" name="isAccepted" />
which is equivalent to property []
and event binding()
syntax
<input
[ngModel]="isAccepted"
(isAcceptedChange)="isAccepted==$event"
type="checkbox"
name="isAccepted"
/>
In typescript component
@Input() ngModel;
@Output() isAcceptedChange = new EventEmitter();
Complete example HTML code:
<h3>Checkbox Basic Two-way binding Example</h3>
<div>
<input [(ngModel)]="isAccepted" type="checkbox" name="isAccepted" />Is
Accepted
<h1>{{ isAccepted }}</h1>
>
</div>
In the Typescript component,
- Declare property variable with type and optional default value.
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-checkbox-component-basic",
templateUrl: "./checkbox-component-basic.component.html",
styleUrls: ["./checkbox-component-basic.component.css"],
})
export class CheckboxComponentBasicComponent implements OnInit {
constructor() {}
isAccepted = true;
ngOnInit() {}
}
This is how two-way binding works in the Angular checkbox in input forms
Angular Dynamic Checkbox example
This example explains about typescript has a json object which has a list of values, and creates a dynamic checkbox.
IN Typescript create an interface to hold the list of values.
export interface Role {
id: number;
name: string;
checked?: boolean;
}
In the typescript component, the Roles object is initialized with data. However, this can be retrieved from a database called Http GET Service. This will not be covered here.
You can have the Role object checked value with true or false to have the checkbox checked by default. And also write getter- selectedCheckboxList which retrieves the user-selected checkbox json object.
import { Component, OnInit } from "@angular/core";
import { Role } from "../role";
@Component({
selector: "app-dynamic-checkbox-list",
templateUrl: "./dynamic-checkbox-list.component.html",
styleUrls: ["./dynamic-checkbox-list.component.css"],
})
export class DynamicCheckboxListComponent implements OnInit {
public roles: Role[];
constructor() {}
ngOnInit() {
this.roles = [
{
id: 1,
name: "users",
checked: true,
},
{
id: 2,
name: "admin",
checked: false,
},
{
id: 3,
name: "Support",
checked: true,
},
{
id: 4,
name: "manager",
checked: false,
},
];
}
get selectedCheckboxList() {
return this.roles.filter((item) => item.checked);
}
}
In the Html template,
- Iterate roles object using *
ngFor
directive - Added input checkbox with binding iterated checked property, which works two-way binding
- Added the label with the object name value
- Display the json object with a selected list of checkbox values.
<h1>Dynamic Checkbox List Example</h1>
<ul>
<li *ngFor="let role of roles">
<input type="checkbox" [(ngModel)]="role.checked" />
<label>{{role.name}}</label>
</li>
</ul>
And the selected Object is
<pre>{{this.selectedCheckboxList | json}}</pre>
This way, how we bind the dynamic checkbox from json object and get the selected checkbox list.
How to get the checkbox value using the change event handler?
Sometimes, we need to track the checkbox state changes.
Like a JavaScript event handler, Angular provides a change event.
In the Html template, Added (change) to input element with event handler - termsChange. This accepts $event parameter.
<input (change)="termsChange($event)" value="terms" type="checkbox" /> Terms
In the Typescript component,
Provide the function with a parameter of any type.
Selected checkbox value can get using target.checked property
termsChange(selected: any): void {
console.log(
selected.target.name,
selected.target.value,
selected.target.checked
);
}
Inside a function, Retrieved the checkbox name and value and checked whether or not This way, You can get the selected check box value in Angular and also call the function while the checkbox is checked.
How can you know checkbox is checked
or not? Inside a change call-back handler, write the following lines of code
if (selected.target.checked) {
//checked
// own logic
} else {
// not checked
// logic
}
Stackblitz example
you can find this post complete code example🔗 at
Conclusion
These tutorials covered angular checkbox tutorials with ngmodal
binding, dynamic list, retrieve the value with examples.
You can see Other Angular Posts
- Angular Click Event example
- Angular Button Click Event
- Fix for Angular require typescript version
- Convert Number to Words
- Detect @input() bindings changes in Angular?
- print application package json version in angular
- Compodoc angular documentation
- Read More/Less Button Link in Angular
- Angular 15 GUID example
- Multiple ways to get input text value in Angular
- Add Google Fonts in Angular
- Angular Media Query Styles