0

When key1 checkbox is checked, I want to check and disable key2 checkbox

HTMLcode

<input class="form-check-input" type="checkbox" formControlName="key1" id="key1" (click)="key1Click()">
            <label for="key1" class="form-check-label">Key 1</label>
            <input class="form-check-input" formControlName="key2" type="checkbox" id="key2">
            <label for="key2" class="form-check-label">Key 2</label>

Typescript code for checkbox

keyClick() {

let x = <HTMLInputElement>document.getElementById("key1");
let y = <HTMLInputElement>document.getElementById("key2");
if (x.checked) {
  y.checked = true;
  y.disabled = true;
}
else {
  y.checked = false;
  y.disabled = false;
}

}

By using this code key2 checkbox is checked and disabled. But the boolean value of key2 checkbox remains false. Any suggestions on how can I change the boolean value of key2 checkbox to true when I click key1 checkbox I am using Angular 8 and its reactive forms module.I am new to angular.

4
  • 1
    Do not never ever manipulate DOM elements directly with Angular. I don't know what you really want to achieve, but don't you think that radio buttons could be a better choice? Commented May 16, 2020 at 15:02
  • Thanks for the suggestion. Whenever key1 checkbox is clicked I want to check (boolean value = true) and disable key2 checkbox . Is there any way I can achieve that? Commented May 16, 2020 at 16:39
  • if you want only one checkbox to be checked at a time, go for radio buttons, instead of using checkboxes. Commented May 16, 2020 at 16:47
  • @AbhishekTewari I want them both checked when I click key1 checkbox Commented May 16, 2020 at 16:49

1 Answer 1

0

You could subscribe to the valueChanges observable of the first checkbox,i.e., key1.

Demo snippet:

this.formName.get("key1").valueChanges.subscribe(val=>{
    if(val)
    //enable the second checkbox
    else 
    //disable the second checkbox
});

where formName is the name of your reactive form. Also don't forget to unsubscribe to this observable on component destroy.

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

3 Comments

I will check this method. Thanks for the reply.
Kindly upvote and accept the answer if it solves your problem.
@Pratik Happy to help. :) Kindly upvote the answer.

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.