nativescript-checkbox icon indicating copy to clipboard operation
nativescript-checkbox copied to clipboard

Event Firing

Open DaljitBhail opened this issue 6 years ago • 3 comments

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

DaljitBhail avatar Nov 02 '17 16:11 DaljitBhail

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.

bufke avatar Jan 20 '19 15:01 bufke

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

aiya000 avatar Jul 30 '19 04:07 aiya000

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

jcfrane avatar Aug 07 '19 06:08 jcfrane