How to Check if a Checkbox is Checked or not in Angular?

To check if a checkbox is checked or not in Angular, you can pass the $event object inside the change event handler function. And inside the event handler function you need to check the value of the event.target.checked.

If the value of the event.target.checked is true then the checkbox is checked. Otherwise, it is unchecked.

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

The doSomething() function gets called every time the checkbox value changes. You need to define the doSomething() function inside your ts file:

doSomething(event:any){
  
  if(event.target.checked==true){
    console.log('checkbox is checked');
  }
  else{
    console.log('checkbox is unchecked');
  }
}

Method 2: Using the ngModel directive

An alternative solution could be to bind the checkbox with a flag(eg. isChecked) using the ngModel directive. Now, whenever the checkbox is checked or unchecked the value of the flag also changes accordingly.

That is, if the checkbox is checked the value of the flag becomes true and if it unchecked, the value of the flag becomes false. This whole process is implicitly done by Angular due to the ngModel directive.

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

Add the below code in your ts file:

isChecked: boolean = false;  // Boolean flag

doSomething(){
  
  if(this.isChecked==true){
    console.log('checkbox is checked');
  }
  else{
    console.log('checkbox is unchecked');
  }
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts