Reputation: 2893
My view is
<Switch checked="{{ active }}" propertyChange="onCheckChange"/>
exports.onCheckChange = function(args)
{
//Api Service call
}
Actually I am binding the active value by API
call and the issue is that onCheckChange
gets executed during the initial binding with false value, so whenever I initially set the active==true
by api service call and load the page, the onCheckChange
is executed with checked==false
, can anyone give me an idea about this please.
Note: Beginner in Nativescript
Upvotes: 2
Views: 415
Reputation: 7997
Wanted to share my answer to this, as two-way data binding isn't working with a <Switch>
for some reason, gives the error:
https://github.com/NativeScript/NativeScript/issues/4694
And in my case, I had a list of items which next to each I wanted to give a Switch
to turn on/off .. it was a part of a list ( for loop ) so I had to have some kind of data-binding for each switch on the items list.
I wrote it like so:
# Instead of two-way data binding which result an error
<Switch [checked]="item.checked">
# I wrote it as non binding:
<ng-template let-item="item" let-index="index">
<StackLayout>
<Switch checked="{{ item.checked }}">
</StackLayout>
</ng-template>
And to answer the above question what was missing for you was also the $event
so an example of how I used it as a list vs a single switch - I passed both index
and $event
to the function:
# html
<Switch checked="{{ item.checked }}" (checkedChange)="switched(index, $event)">
# ts
import { Switch } from "@nativescript/core";
switched(index, args: EventData) {
let switch_item = args.object as Switch;
this.my_items_array[index].checked = switch_item.checked;
}
Upvotes: 0
Reputation: 12547
The two-way data-binding (described by leoncc
) might be specific to the Angular NativeScript.
Here's a workaround without the two-way data binding, hopefully it will be easier to port to the plain NativeScript if needs be.
In the controller we can get the state of the Switch
with a ViewChild
query:
checked = true;
@ViewChild ('switch') private switch: ElementRef;
switched() {
let switch: Switch = this.switch.nativeElement;
this.checked = switch.checked}
And in the template we should invoke the switched
change handler:
<Switch #switch [checked]="checked" (checkedChange)="switched()" class="switch"></Switch>
Upvotes: 0
Reputation: 233
I battled with the checked property a lot so I opted for two-way binding, which behaves as expected:
// test.xml
<Switch [(ngModel)]="isUnicorn"></Switch>
// test.ts
isUnicorn: boolean = true;
......
if (this.isUnicorn) {
console.log("It is a unicorn");
}
Note that to get two-way binding to work you need to import NativeScriptFormsModule in app.module.ts or applicable module for instance:
// app.module.ts
import { NativeScriptFormsModule } from "nativescript-angular/forms";
......
@NgModule({
imports: [
NativeScriptFormsModule,
......
],
exports: [
NativeScriptFormsModule,
......
],
......
Upvotes: 0