max2020 max2020 - 1 month ago 7
TypeScript Question

Angular detect If checkbox is checked from the .ts

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?

Answer Source

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;
    }
}