Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nativescript Switch prevent change event firing on initial binding

Hi my template is something like the below

<ListView [items]="modules">
    <template let-item="item" >
        <StackLayout orientation="vertical">
                <Switch (checkedChange)="onSwitchModule(item.id,$event)" [checked]="item.active"></Switch>
        </StackLayout>
    </template>
</ListView>

My controller is

ngOnInit() {
    this._moduleService.getUserModules()
        .subscribe(
            response=>{
              this.modules = response.data;
            }
        )

}

onSwitchModule(itemId) {
   console.log(itemID); //Gets called on initial true binding on switch checked
}

The onSwitchModule get called everytime the page loads with item.active is true on any item, how to handle this ?

NOTE: Beginner in Nativescript

like image 457
Niyaz Avatar asked Oct 30 '22 15:10

Niyaz


1 Answers

What I did to overcome this is I watch for tap events instead of checkedChange:

<Switch (tap)="switchClicked" [checked]="item.active"></Switch>

and in the callback, you can get the current item from bindingContext:

function switchClicked(args) {
  const item = args.object.bindingContext.item;
}
like image 58
Nicu Surdu Avatar answered Nov 15 '22 12:11

Nicu Surdu