0

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?

1

1 Answer 1

1

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

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

2 Comments

Thanks this makes a lot of sense, just to make it fully clear for me (really new to Angular), the [(ngModel)] is holding the value of a checkbox and "isChecked" could be replaced with gibberish (i.e, just a name)?
Its called two way binding. you can read here : malcoded.com/posts/angular-data-binding . you bind the Variable stored in ts file directly with dom element. Any change gets reflected in both the side.

Your Answer

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