nstudio / nativescript-checkbox

NativeScript plugin for checkbox UI component
Other
119 stars 56 forks source link

Event Firing #71

Open DaljitBhail opened 6 years ago

DaljitBhail commented 6 years ago

When the checkbox is tapped it fires the checkChangedEvent. But annoyingly if the checkbox value is changed in code this also fires the event.

bufke commented 5 years ago

This can cause trouble when trying to use nativescript-checkbox in a declarative manner. For example (using angular)

  <button text="make true" (tap)="makeTrue()"></button>
  <ns-checkbox [checked]="isChecked" (tap)="toggleChecked()"></ns-checkbox>

I want my checkbox component to always show the "isChecked" boolean. As is, CheckBox it's fairly easy to get out of sync. The boolean might be true but it appears to be unchecked. I was able to work around this by making a ns-checkbox component like this:

import {
  Component,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef
} from "@angular/core";

@Component({
  selector: "ns-checkbox",
  template: `
    <CheckBox
      #CB
      [checked]="checked"
      (tap)="onTap()"
      (checkedChange)="checkedChange($event.value)"
    ></CheckBox>
  `,
  styleUrls: ["./ns-checkbox.component.css"]
})
export class NsCheckboxComponent {
  @Input() checked = false;
  @Output() tap = new EventEmitter();
  @ViewChild("CB") checkbox: ElementRef;

  onTap() {}

  checkedChange(isChecked: boolean) {
    if (isChecked !== this.checked) {
      this.checkbox.nativeElement.checked = this.checked;
    }
  }
}

The trick is to ignore the CheckBox's tap. Then for checkChange I see what it should be according to the checked inbox and ensure it's set to that. Tested in Android.

aiya000 commented 5 years ago

I fell into this problem too until I found this answer :sob:

jcfrane commented 5 years ago

I literally spent my whole day for this problem. Thanks @bufke