This document provides a comprehensive guide on how to get checkbox checked values across all Angular versions, from AngularJS (1.x) to the latest Angular (17+).
html
<div ng-app="myApp" ng-controller="MyController">
<input type="checkbox" ng-model="isChecked" />
<p>Checkbox is: {{isChecked}}</p>
<!-- Template - Default Checked -->
<input type="checkbox" ng-model="isCheckedByDefault" />
<p>Default checked: {{isCheckedByDefault}}</p>
<!-- Using checked attribute -->
<input type="checkbox" ng-model="staticChecked" />
<p>Static checked: {{staticChecked}}</p>
</div>
javascript
angular.module('myApp', [])
.controller('MyController', function($scope) {
// Basic checkbox values
$scope.isChecked = false;
$scope.isCheckedByDefault = true; // Checked by default
$scope.staticChecked = true;
// Watch for changes
$scope.$watch('isChecked', function(newVal, oldVal) {
if (newVal !== oldVal) {
console.log('isChecked changed:', newVal);
}
});
});
html
<!-- Template -->
<div ng-app="myApp" ng-controller="MyController">
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected" ng-change="updateSelection()">
{{item.name}}
</div>
</div>
javascript
// Controller
angular.module('myApp', [])
.controller('MyController', function($scope) {
$scope.items = [
{name: 'Option 1', selected: false},
{name: 'Option 2', selected: true},
{name: 'Option 3', selected: false}
];
$scope.updateSelection = function() {
var selected = $scope.items.filter(function(item) {
return item.selected;
});
console.log('Selected items:', selected);
};
});
typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<!-- Default unchecked -->
<input type="checkbox"
[(ngModel)]="isChecked"
(change)="onCheckboxChange($event)">
<p>Checkbox is: {{isChecked}}</p>
<!-- Default checked -->
<input type="checkbox"
[(ngModel)]="isCheckedByDefault"
(change)="onDefaultCheckboxChange($event)">
<p>Default checked: {{isCheckedByDefault}}</p>
<!-- Using checked attribute -->
<input type="checkbox"
[(ngModel)]="staticChecked"
checked>
<p>Static checked: {{staticChecked}}</p>`
})
export class AppComponent {
isChecked: boolean = false;
isCheckedByDefault: boolean = true; // Checked by default
staticChecked: boolean = true;
onCheckboxChange(event: any) {
console.log('Checkbox changed:', event.target.checked);
this.isChecked = event.target.checked;
}
onDefaultCheckboxChange(event: any) {
console.log('Default checkbox changed:', event.target.checked);
this.isCheckedByDefault = event.target.checked;
}
}
template: `
<form [formGroup]="checkboxForm">
<!-- Default unchecked -->
<input type="checkbox" formControlName="isChecked">
<p>Value: {{checkboxForm.get('isChecked')?.value}}</p>
<!-- Default checked -->
<input type="checkbox" formControlName="isCheckedByDefault">
<p>Default checked: {{checkboxForm.get('isCheckedByDefault')?.value}}</p>
<!-- Programmatically set checked -->
<input type="checkbox" formControlName="programmaticChecked">
<p>Programmatic: {{checkboxForm.get('programmaticChecked')?.value}}</p>
<button type="button" (click)="toggleProgrammatic()">Toggle Programmatic</button>
</form>
})
export class AppComponent {
checkboxForm = new FormGroup({
isChecked: new FormControl(false),
isCheckedByDefault: new FormControl(true), // Checked by default
programmaticChecked: new FormControl(false)
});
ngOnInit() {
// Set checked programmatically after initialization
this.checkboxForm.get('programmaticChecked')?.setValue(true);
this.checkboxForm.get('isCheckedByDefault')?.valueChanges.subscribe(value => {
console.log('Default checkbox value changed:', value);
});
}
toggleProgrammatic() {
const current = this.checkboxForm.get('programmaticChecked')?.value;
this.checkboxForm.get('programmaticChecked')?.setValue(!current);
}
}
//app.component.ts
template: `
<form [formGroup]="form">
<!-- Default unchecked -->
<input type="checkbox" formControlName="isChecked">
<p>Current value: {{form.get('isChecked')?.value}}</p>
<!-- Default checked -->
<input type="checkbox" formControlName="isCheckedByDefault">
<p>Default checked: {{form.get('isCheckedByDefault')?.value}}</p>
<!-- Multiple ways to set default checked -->
<input type="checkbox" formControlName="anotherChecked">
<p>Another checked: {{form.get('anotherChecked')?.value}}</p>
</form>
<button (click)="resetToDefaults()">Reset to Defaults</button>
<button (click)="setAllChecked()">Check All</button>
<button (click)="setAllUnchecked()">Uncheck All</button>`,
})
export class AppComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
isChecked: [false],
isCheckedByDefault: [true], // Default checked using FormBuilder
anotherChecked: [false],
});
// Set checked after form creation
this.form.get('anotherChecked')?.setValue(true);
// Subscribe to value changes
this.form.get('isCheckedByDefault')?.valueChanges.subscribe((value) => {
console.log('Default checkbox value:', value);
});
}
}
template: `
<form [formGroup]="form">
<div formArrayName="checkboxes">
<div *ngFor="let control of checkboxes.controls; let i = index">
<input type="checkbox" [formControlName]="i">
{{options[i]}}
</div>
</div>
</form>
<p>Selected: {{getSelectedValues() | json}}</p>
<button (click)="selectDefaults()">Select Defaults</button>
<button (click)="selectAll()">Select All</button>
<button (click)="clearAll()">Clear All</button>`
})
export class AppComponent implements OnInit {
form: FormGroup;
options = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];
// Define which checkboxes should be checked by default
defaultSelections = [false, true, false, true]; // Options 2 and 4 checked
constructor(private fb: FormBuilder) {}
ngOnInit() {
// Initialize with default selections
this.form = this.fb.group({
checkboxes: this.fb.array(this.defaultSelections)
});
// Alternative way to set defaults after creation
// this.form = this.fb.group({
// checkboxes: this.fb.array([false, false, false, false])
// });
// this.setDefaultSelections();
}
}
template: `
<form [formGroup]="form">
<input type="checkbox" formControlName="isChecked">
<p>Value: {{checkboxValue}}</p>
</form>`
})
export class AppComponent implements OnInit {
form: FormGroup;
checkboxValue: boolean = true;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
isChecked: [true]
});
// Enhanced subscription with RxJS operators
this.form.get('isChecked')?.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged()
).subscribe(value => {
this.checkboxValue = value;
console.log('Debounced checkbox value:', value);
});
}
}
template: `
<form [formGroup]="form">
<input type="checkbox"
formControlName="isChecked"
(change)="onCheckboxChange($event)">
<p>Value: {{form.get('isChecked')?.value}}</p>
</form>`,
})
export class AppComponent implements OnInit, OnDestroy {
form: FormGroup;
private destroy$ = new Subject<void>();
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
isChecked: [true],
});
this.form
.get('isChecked')
?.valueChanges.pipe(takeUntil(this.destroy$))
.subscribe((value) => {
console.log('Checkbox value changed:', value);
});
}
onCheckboxChange(event: Event) {
const target = event.target as HTMLInputElement;
console.log('Event-based value:', target.checked);
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
template: `
` }) export class AppComponent implements OnInit { form!: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit(): void { this.form = this.fb.group({ isChecked: new FormControl(false, { nonNullable: true }) }); this.form.controls.isChecked.valueChanges.subscribe(value => { console.log(‘Typed checkbox value:’, value); }); } checkboxValue(): boolean { return this.form.controls.isChecked.value; } toggleCheckbox(): void { const currentValue = this.form.controls.isChecked.value; this.form.controls.isChecked.setValue(!currentValue); } }
template: `<form [formGroup]="form">
<!-- Reactive form with default checked -->
<input type="checkbox"
formControlName="isChecked"
(change)="updateSignal()">
<p>Form Value: {{form.controls.isChecked.value}}</p>
<p>Signal Value: {{checkboxSignal()}}</p>
<!-- Default checked reactive form -->
<input type="checkbox" formControlName="defaultChecked">
<p>Default Checked Form: {{form.controls.defaultChecked.value}}</p>
</form>
<!-- Direct signal binding with default checked -->
<input type="checkbox"
[checked]="directCheckbox()"
(change)="toggleDirectCheckbox()">
<p>Direct Signal: {{directCheckbox()}}</p>
<!-- Signal initialized as checked -->
<input type="checkbox"
[checked]="preCheckedSignal()"
(change)="togglePreChecked()">
<p>Pre-checked Signal: {{preCheckedSignal()}}</p>
<div>
<button (click)="setAllChecked()">Check All</button>
<button (click)="setAllUnchecked()">Uncheck All</button>
<button (click)="resetToDefaults()">Reset to Defaults</button>
</div>`
})
export class AppComponent {
private fb = new FormBuilder();
// Traditional reactive form with default values
form = this.fb.group({
isChecked: [false],
defaultChecked: [true] // Default checked
});
// Signal-based approach
checkboxSignal = signal(false);
directCheckbox = signal(false);
preCheckedSignal = signal(true); // Default checked signal
constructor() {
// Set some defaults after initialization
this.directCheckbox.set(true);
// Watch form changes and update signal
this.form.controls.isChecked.valueChanges.subscribe(value => {
this.checkboxSignal.set(value || false);
});
}
updateSignal(): void {
const value = this.form.controls.isChecked.value;
this.checkboxSignal.set(value || false);
console.log('Updated signal:', this.checkboxSignal());
}
toggleDirectCheckbox(): void {
this.directCheckbox.update(value => !value);
console.log('Direct checkbox toggled:', this.directCheckbox());
}
setAllChecked(): void {
this.form.patchValue({
isChecked: true,
defaultChecked: true
});
this.checkboxSignal.set(true);
this.directCheckbox.set(true);
this.preCheckedSignal.set(true);
}
checkboxStatus = computed(() =>
this.preCheckedSignal() ? 'Checked': 'Unchecked'
);
}
template: `
<form [formGroup]="form">
<!-- Default checked form control -->
<input type="checkbox" formControlName="isChecked">
@if (form.controls.isChecked.value) {
<p>Checkbox is checked! âś…</p>
} @else {
<p>Checkbox is unchecked ❌</p>
}
<!-- Multiple checkboxes with new control flow -->
@for (option of options; track option.id) {
<label>
<input type="checkbox"
[checked]="selectedOptions().includes(option.id)"
(change)="toggleOption(option.id)">
{{option.name}}
@if (option.defaultSelected) {
<span class="default-indicator">(Default)</span>
}
</label>
}
</form>
<div>
<h3>Selected Options:</h3>
@for (id of selectedOptions(); track id) {
<span>{{getOptionName(id)}} </span>
} @empty {
<span>No options selected</span>
}
</div>
<div>
<button (click)="selectDefaults()">Select Defaults</button>
<button (click)="selectAll()">Select All</button>
<button (click)="clearAll()">Clear All</button>
</div>`
})
export class AppComponent {
private fb = new FormBuilder();
// Form with default checked value
form = this.fb.group({
isChecked: [true] // Default checked
});
options = [
{ id: 1, name: 'Option 1', defaultSelected: false },
{ id: 2, name: 'Option 2', defaultSelected: true },
{ id: 3, name: 'Option 3', defaultSelected: false },
{ id: 4, name: 'Option 4', defaultSelected: true }
];
// Initialize with default selections
selectedOptions = signal<number[]>([2, 4]); // Options 2 and 4 selected by default
constructor() {
// Alternative: Set defaults after initialization
// this.setDefaultSelections();
}
toggleOption(id: number): void {
this.selectedOptions.update(current => {
const index = current.indexOf(id);
if (index > -1) {
return current.filter(optionId => optionId !== id);
} else {
return [...current, id];
}
});
}
getOptionName(id: number): string {
return this.options.find(option => option.id === id)?.name || '';
}
selectDefaults(): void {
const defaultIds = this.options
.filter(option => option.defaultSelected)
.map(option => option.id);
this.selectedOptions.set(defaultIds);
}
selectAll(): void {
const allIds = this.options.map(option => option.id);
this.selectedOptions.set(allIds);
}
clearAll(): void {
this.selectedOptions.set([]);
}
private setDefaultSelections(): void {
const defaultIds = this.options
.filter(option => option.defaultSelected)
.map(option => option.id);
this.selectedOptions.set(defaultIds);
}
}
This guide covers checkbox handling across all Angular versions, showing the evolution from AngularJS’s two-way binding to modern Angular’s signals and reactive forms. Choose the approach that matches your Angular version and project requirements.
Always consider accessibility, type safety, and proper subscription management regardless of the Angular version you’re using.
Mixed scenarios – Some checked, some unchecked by default
Work with our skilled Angular developers to accelerate your project and boost its performance.
Hire Angular Developers