Angular Checkbox Example

By Arvind Rai, 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.

1. With FormControl

Find the code to create checkbox using FormControl.
TS code:
isActive = new FormControl(false); 
HTML code:
<input type="checkbox" [formControl]="isActive">

{{isActive.value}} 
When checkbox is checked, its value will be true otherwise false.

2. With ngModel

Using ngModel, we can bind the initial value of checkbox as well as can fetch the updated value.
TS code:
isPresent= true; 
HTML code:
<input type="checkbox" [(ngModel)]="isPresent">

{{isPresent}} 
As the value of isPresent is true, initially checkbox will be checked. If we uncheck the checkbox, the value of isPresent will be false.

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"> 
We can dynamically check/uncheck the checkbox using checked property binding.
TS code:
isPresent= true; 
HTML code:
<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);
} 
HTML code:
<input type="checkbox" (change)="onChangeUserStatus($event)"> 

5. disabled

To disable a checkbox, use disabled attribute as below.
<input type="checkbox" disabled>
<input type="checkbox" disabled="true"> 
To disable/enable checkbox dynamically use property binding.
TS code:
isDisabled = true; 
HTML code:
<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}); 
HTML code:
<input type="checkbox" [formControl]="isUserActive"> 
When checkbox is disabled, user will not be able to check/uncheck it.

6. Validation

Using ngModel
To 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]); 
HTML code:
<input type="checkbox" [formControl]="isTCAccepted">
<div *ngIf="isTCAccepted.invalid" ngClass="error">
	Select T & C.
</div> 

{{isTCAccepted.status}} 
When checkbox is checked, status will be VALID otherwise INVALID.

7. Setting Default Value

Find the code to make checkbox checked by default.
1. Using checked
TS code:
isMarried = true; 
HTML code:
<input type="checkbox" [checked]="isMarried"> 
2. Using ngModel
<input type="checkbox" [ngModel]="isMarried"> 
3. Using FormControl
TS code:
isMarried = new FormControl(true); 
HTML code:
<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 },
     ------
]; 
Now iterate the array to create multiple checkbox.
For template-driven form:
HTML code:
<div *ngFor="let hobby of allHobbies">
	<input type="checkbox" [name]="hobby.hid" [(ngModel)]="hobby.isChecked"> {{hobby.title}}
</div> 
TS code:
selectedHobbies = this.allHobbies.filter(hobby => hobby.isChecked == true); 
For reactive form :
TS code:
empForm = this.formBuilder.group({
    ------
	hobbies: this.formBuilder.array([]),
});
this.allHobbies.forEach(() => {
	(this.empForm.get('hobbies') as FormArray).push(new FormControl(false));
}); 
HTML code:
<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> 
emp-reactive.component.ts
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);
	}
} 
emp-service.ts
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> 
emp-template-driven.component.ts
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);
	}
} 
employee.ts
export interface Employee {
	empName: string;
	isMarried: boolean;
	wfh: boolean;
	hobbies: any[];
	isTCAccepted: boolean;
} 

11. Output

Find the print-screen of the output.
Angular Checkbox Example

12. Reference

13. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us