25

I am using Angular 4 and I have a checkbox on my component on the component's html template file:

<input type="checkbox" (change)="canBeEditable($event)">

On my component's .ts file I have this which set's the value to true.

toggleEditable() {
    this.contentEditable = true;
}

My problem is that I only want the value changed IF the checkbox IS checked.

So it would look something like:

toggleEditable() {
    if (checkbox is checked) {
      this.contentEditable = true;
    }
}

How can I do this?

2
  • 2
    Possible duplicate of Check if checkbox element is checked in TypeScript Commented Aug 18, 2017 at 18:19
  • That doesn't work on my app. HTMLInputElement is not a type it knows Commented Aug 18, 2017 at 18:30

1 Answer 1

51

You need to check event.target.checked to solve this issue. This is how you can achieve that:

<input type="checkbox" (change)="toggleEditable($event)">

In your component's .ts:

toggleEditable(event) {
     if ( event.target.checked ) {
         this.contentEditable = true;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Is there a way to do this for radio buttons as well? event.target.checked always results as true after the radio button has been clicked once.
What would be type of 'event' in this case? if i use typescript.
@nikhil do you have an answer for this?
Just do event.checked in typescript (you can print the variable event to see what field it contains, this would have easily give you the answer :) )
umm, it's a toggle. Why not just: html - <input ... (change)="toggleEditable()">, ts - toggleEditable() { this.editable = !this.editable; }

Your Answer

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