Checkbox in Angular
January 07, 2024
On this page, we will learn to create checkbox in our Angular application. Checkbox can be created using ngModel
, formControl
and formControlName
. Checkbox has a checked
attribute that if true, it will be checked. On check/uncheck, change
event triggers. Checkbox can be disabled using disabled
attribute. It can also be disabled using FormControl
. We can validate the checkbox using required attribute and Validators.requiredTrue
.
Now find the checkbox examples in detail.
Contents
1. With FormControl
Find the code to create checkbox usingFormControl
.
TS code:
isActive = new FormControl(false);
<input type="checkbox" [formControl]="isActive"> {{isActive.value}}
2. With ngModel
UsingngModel
, we can bind the initial value of checkbox as well as can fetch the updated value.
TS code:
isPresent= true;
<input type="checkbox" [(ngModel)]="isPresent"> {{isPresent}}
3. checked
checked
is a property of checkbox that decides if checkbox will be checked or unchecked by default. To keep checkbox checked by default, write code as below.
<input type="checkbox" checked> <input type="checkbox" checked="true">
checked
property binding.
TS code:
isPresent= true;
<input type="checkbox" [checked]="isPresent">
4. change Event
change
event of checkbox triggers on check/uncheck. To fetch checked value, use $event.target.checked
.
TS code:
onChangeUserStatus(ev: any) { console.log(ev.target.checked); }
<input type="checkbox" (change)="onChangeUserStatus($event)">
5. disabled
To disable a checkbox, usedisabled
attribute as below.
<input type="checkbox" disabled> <input type="checkbox" disabled="true">
TS code:
isDisabled = true;
<input type="checkbox" [disabled]="isDisabled">
Using FormControl :
To disable a checkbox using
FormControl
, create its instance by passing disabled as true.
TS code:
isUserActive = new FormControl({value: false, disabled: true});
<input type="checkbox" [formControl]="isUserActive">
6. Validation
Using ngModelTo validate checkbox, use required attribute and fetch status using template reference variable.
<input type="checkbox" name="isTCAccepted" [(ngModel)]="isTCAccepted" required #tc="ngModel"> <div *ngIf="tc.invalid" ngClass="error"> Select T & C. </div>
Using FormControl :
To validate a
FormControl
to be checked, use Validators.requiredTrue
.
TS code:
isTCAccepted = new FormControl({value: false, disabled: false}, [Validators.requiredTrue]);
<input type="checkbox" [formControl]="isTCAccepted"> <div *ngIf="isTCAccepted.invalid" ngClass="error"> Select T & C. </div> {{isTCAccepted.status}}
7. Setting Default Value
Find the code to make checkbox checked by default.1. Using checked
TS code:
isMarried = true;
<input type="checkbox" [checked]="isMarried">
<input type="checkbox" [ngModel]="isMarried">
TS code:
isMarried = new FormControl(true);
<input type="checkbox" [formControl]="isMarried">
8. Creating Multiple Checkbox Dynamically
We can create multiple checkbox dynamically and access the selected checkbox.Suppose we have an array of hobbies that can be selected by employee while registering.
const allHobbies = [ { hid: 1, title: 'Reading Books', isChecked: false }, { hid: 2, title: 'Listening Music', isChecked: false }, ------ ];
For template-driven form:
HTML code:
<div *ngFor="let hobby of allHobbies"> <input type="checkbox" [name]="hobby.hid" [(ngModel)]="hobby.isChecked"> {{hobby.title}} </div>
selectedHobbies = this.allHobbies.filter(hobby => hobby.isChecked == true);
TS code:
empForm = this.formBuilder.group({ ------ hobbies: this.formBuilder.array([]), }); this.allHobbies.forEach(() => { (this.empForm.get('hobbies') as FormArray).push(new FormControl(false)); });
<div formArrayName="hobbies"> <div *ngFor="let hobby of allHobbies; let i = index"> <input type="checkbox" [formControlName]="i"> {{hobby.title}} </div> </div>
9. Using Reactive Form
Here I will create a reactive form that will contain checkboxes. We will create an employee form and fetch its data on form submit.emp-reactive.component.html
<h3>Employee Reactive Form</h3> <p *ngIf="isValidFormSubmitted && empForm.pristine" ngClass="success"> Form submitted successfully. </p> <form [formGroup]="empForm" (ngSubmit)="onFormSubmit()"> <table> <tr> <td>Name:</td> <td> <input formControlName="empName"> <div *ngIf="empForm.get('empName')?.invalid && isValidFormSubmitted != null && !isValidFormSubmitted" ngClass="error"> Name required. </div> </td> </tr> <tr> <td>Work from home?</td> <td> <input type="checkbox" formControlName="wfh"> </td> </tr> <tr> <td>Are you married? </td> <td> <input type="checkbox" formControlName="isMarried"> </td> </tr> <tr> <td>Select Hobbies: </td> <td> <div formArrayName="hobbies"> <div *ngFor="let hobby of allHobbies; let i = index"> <input type="checkbox" [formControlName]="i" (change)="onHobbyChange($event)"> {{hobby.title}} </div> </div> </td> </tr> <tr> <td>Agree to T & C?</td> <td> <input type="checkbox" formControlName="isTCAccepted"> <div *ngIf="empForm.get('isTCAccepted')?.invalid && isValidFormSubmitted != null && !isValidFormSubmitted" ngClass="error"> Select T & C. </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> <button type="button" (click)="setDefaultValues()">Set Default</button> <button type="button" (click)="reset()">Reset</button> </td> </tr> </table> </form>
import { Component, OnInit } from '@angular/core'; import { FormArray, FormBuilder, FormControl, ReactiveFormsModule, Validators } from '@angular/forms'; import { EmpService } from './services/emp-service'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-reactive', standalone: true, imports: [ReactiveFormsModule, CommonModule], templateUrl: './emp-reactive.component.html', styleUrls: ['./style.css'] }) export class EmpReactiveComponent implements OnInit { isValidFormSubmitted!: boolean; constructor(private formBuilder: FormBuilder, private empService: EmpService) { } empForm = this.formBuilder.group({ empName: ['', Validators.required], wfh: false, isMarried: false, hobbies: this.formBuilder.array([]), isTCAccepted: new FormControl(false, Validators.requiredTrue) }); allHobbies!: any[]; ngOnInit() { this.allHobbies = this.empService.getAllHobbies(); this.allHobbies.forEach(hobby => { this.hobbies.push(new FormControl(false)); }); } onFormSubmit() { this.isValidFormSubmitted = false; if (this.empForm.invalid) { return; } this.isValidFormSubmitted = true; this.empService.createEmployee(this.empForm.value); let i = 0; this.empForm.value.hobbies?.forEach(h => { if (h === true) { console.log(this.allHobbies[i].title); } i++; }); this.reset(); } reset() { this.empForm.reset(); } get hobbies() { return this.empForm.get('hobbies') as FormArray; } setDefaultValues() { this.empForm.patchValue({ empName: 'Mahesh', wfh: true, isMarried: false, isTCAccepted: true }); } onHobbyChange(ob: any) { console.log(ob); } }
import { Injectable } from '@angular/core'; const ALL_HOBBIES = [ { hid: 1, title: 'Music', isChecked: false }, { hid: 2, title: 'Art', isChecked: false }, { hid: 3, title: 'Cricket', isChecked: false }, { hid: 4, title: 'Badminton', isChecked: false }, { hid: 5, title: 'Hockey', isChecked: false } ]; @Injectable({ providedIn: 'root' }) export class EmpService { createEmployee(emp: any) { console.log(emp); } getAllHobbies() { return ALL_HOBBIES; } }
10. Using Template-Driven Form
Here I will create employee form using template-driven form and fetch its data on form submit.emp-template-driven.component.html
<h3>Employee Template-Driven Form</h3> <p *ngIf="isValidFormSubmitted" ngClass="success"> Form submitted successfully. </p> <form #empForm="ngForm" (ngSubmit)="onFormSubmit(empForm)"> <table> <tr> <td>Name:</td> <td> <input name="empName" [(ngModel)]="emp.empName" required #ename="ngModel"> <div *ngIf="ename.invalid && empForm.submitted && !isValidFormSubmitted" ngClass="error"> Name required. </div> </td> </tr> <tr> <td>Work from home?</td> <td> <input type="checkbox" name="wfh" [(ngModel)]="emp.wfh" (change)="onChangeWFH()"> </td> </tr> <tr> <td>Are you married? </td> <td> <input type="checkbox" name="isMarried" [(ngModel)]="emp.isMarried"> </td> </tr> <tr> <td>Select Hobbies:</td> <td> <div *ngFor="let hobby of allHobbies"> <input type="checkbox" ngModel [name]="hobby.hid" [checked]="hobby.isChecked" (change)="hobby.isChecked= !hobby.isChecked"> {{hobby.title}} </div> </td> </tr> <tr> <td>Agree to T & C?</td> <td> <input type="checkbox" name="isTCAccepted" [(ngModel)]="emp.isTCAccepted" required #tc="ngModel"> <div *ngIf="tc.invalid && empForm.submitted && !isValidFormSubmitted" ngClass="error"> Select T & C. </div> </td> </tr> <tr> <td colspan="2"> <button>Submit</button> <button type="button" (click)="setDefaultValues()">Set Default</button> <button type="button" (click)="resetForm(empForm)">Reset</button> </td> </tr> </table> </form>
import { Component, OnInit } from '@angular/core'; import { FormsModule, NgForm } from '@angular/forms'; import { EmpService } from './services/emp-service'; import { Employee } from './domain/employee'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-template', standalone: true, imports: [FormsModule, CommonModule], templateUrl: './emp-template-driven.component.html', styleUrls: ['./style.css'] }) export class EmpTemplateDrivenComponent implements OnInit { isValidFormSubmitted = false; emp = {} as Employee; allHobbies!: any[]; constructor(private empService: EmpService) { } ngOnInit() { this.allHobbies = this.empService.getAllHobbies(); } onFormSubmit(form: NgForm) { this.isValidFormSubmitted = false; if (form.invalid) { return; } this.isValidFormSubmitted = true; this.emp.hobbies = this.allHobbies.filter(hobby => hobby.isChecked == true); this.empService.createEmployee(this.emp); this.resetForm(form); } resetForm(form: NgForm) { form.resetForm(); this.allHobbies.map(hobby => hobby.isChecked = false); } setDefaultValues() { this.emp.empName = 'Pramod'; this.emp.wfh = true; this.emp.isMarried = false; this.emp.isTCAccepted = true; this.allHobbies.map(hobby => { if (hobby.hid == 2) { hobby.isChecked = true; } else { hobby.isChecked = false; } }); } onChangeWFH() { console.log(this.emp.wfh); } }
export interface Employee { empName: string; isMarried: boolean; wfh: boolean; hobbies: any[]; isTCAccepted: boolean; }