问题
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
回答1:
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,
......
],
......
回答2:
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>
来源:https://stackoverflow.com/questions/40914604/nativescript-switch-not-to-fire-initial-binding