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:
- 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() { }
}
- In your component’s HTML file (e.g.,
component.html
), bind the checkbox’schecked
property to theisChecked
variable using Angular’s data binding syntax:
<input type="checkbox" [(ngModel)]="isChecked">
- 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)]
.