Home > front end >  How to check/uncheck a checkbox programmatically in Angular 8?
How to check/uncheck a checkbox programmatically in Angular 8?

Time:04-26

How can I check/uncheck a checkbox programmatically.

<input type="checkbox" formControlName="checkedGender" [checked]="checkedGender" (change)="checkedGender = !checkedGender" disabled />

I have this below angular code but its not able to check/uncheck.

Angular line of code for checking the checkbox:

this.formGroup.controls['checkedGender'].setValue(true);

Similarly Angular line of code for unchecking the checkbox

this.formGroup.controls['checkedGender'].setValue(false);

but none of those are showing any effect on checkbox, am I doing something wrong?

CodePudding user response:

Angular forms api should handle the change for you. So it should not be necessary to assign something to [checked] or (change) because reactive forms are doing this.

So just write

<input type="checkbox" formControlName="checkedGender" disabled>

The state of this checkbox will be set by the forms api

  • Related