How to set checkbox checked value with Angular and JavaScript?

To set the checked value of a checkbox using Angular and JavaScript, you can utilize data binding in Angular to bind the checkbox’s checked property to a boolean variable in your component’s TypeScript code.

To do this we:

  1. In your component’s TypeScript file (e.g., component.ts), define a boolean variable to track the checked state:
import { Component } from '@angular/core';

@Component({
  selector: 'app-checkbox-example',
  templateUrl: './checkbox-example.component.html',
  styleUrls: ['./checkbox-example.component.css']
})
export class CheckboxExampleComponent {
  isChecked: boolean = false;

  constructor() { }
}
  1. In your component’s HTML file (e.g., component.html), bind the checkbox’s checked property to the isChecked variable using Angular’s data binding syntax:
<input type="checkbox" [(ngModel)]="isChecked">
  1. Now, you can manipulate the value of isChecked variable in your component’s TypeScript code to set the checkbox’s checked state programmatically. For example:
// Set checkbox to checked
this.isChecked = true;

// Set checkbox to unchecked
this.isChecked = false;

By updating the value of isChecked variable, Angular will automatically update the checked state of the checkbox in the UI due to the two-way data binding provided by [(ngModel)].