1

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?

1
  • 1
    you should remove [checked] this is already done by the angular forms api. Otherwise you change the value with setValue(false) to uncheck it, but in your code you say (change)="checkedGender = !checkedGender". SetValue triggers a change as well, so you are redundant. Just keep formControlName and work with reactive forms in all means, or use the template and remove the formControlName Commented Apr 25, 2022 at 10:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.