user12421682
user12421682

Reputation:

How to call different methods when checkbox is checked/unchecked in Angular?

In my component class, I have two methods, one for when a checkbox is checked, and one for when a checkbox is unchecked. how do I define this behavior in my template file? this is sort of a pseudo-code of what I expected to have functionality for, though after some time looking around the web I don't see any option like this and can't seem to understand how it should be done

<input type="checkbox" *when checked*="method1()" *when unchecked*="method2()">

how should I implement this?

Upvotes: 0

Views: 1106

Answers (1)

programoholic
programoholic

Reputation: 5194

You can achieve this as below :

in component.html :

<input type="checkbox" [(ngModel)]="isChecked" (change)="handleChange()" />

in component.ts :

handleChange() {
    console.log(this.isChecked);
    if (this.isChecked) {
      this.checkedTrue();
    } else {
      this.checkedFalse();
    }

  }

  checkedTrue() {
    console.log('checked')
  }

  checkedFalse() {
    console.log('unchecked')
}

here is the working demo : demo

Upvotes: 1

Related Questions