How to determine check/uncheck checkbox event in Angular


angular

In Angular, determining when a checkbox is checked or unchecked can be done through event binding. In this post we will check multiple basic ways how to do this.

Template Syntax

You can bind to the change event of the checkbox to detect when its state changes.

<input type="checkbox" (change)="onCheckboxChange($event)">

In your component, you’ll need to define the onCheckboxChange method:

import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <input type="checkbox" (change)="onCheckboxChange($event)">
    <p>Checkbox is {{ isChecked ? 'checked' : 'unchecked' }}</p>
  `
})
export class ExampleComponent {
  public isChecked = false;

  public onCheckboxChange(event: Event) {
    const checkbox = event.target as HTMLInputElement;
    this.isChecked = checkbox.checked;
    console.log(`Checkbox is ${this.isChecked ? 'checked' : 'unchecked'}`);
  }
}

Two-Way Data Binding

For a more straightforward approach, especially if you’re just interested in the state of the checkbox, you can use Angular’s two-way data binding:

<input type="checkbox" [(ngModel)]="isChecked">

In the component:

import { Component } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <input type="checkbox" [(ngModel)]="isChecked">
    <p>Checkbox is {{ isChecked ? 'checked' : 'unchecked' }}</p>
  `
})
export class ExampleComponent {
  isChecked = false;
}
comments powered by Disqus