您好我的模板如下所示
<ListView [items]="modules">
<template let-item="item" >
<StackLayout orientation="vertical">
<Switch (checkedChange)="onSwitchModule(item.id,$event)" [checked]="item.active"></Switch>
</StackLayout>
</template>
</ListView>
我的控制器是
ngOnInit() {
this._moduleService.getUserModules()
.subscribe(
response=>{
this.modules = response.data;
}
)
}
onSwitchModule(itemId) {
console.log(itemID); //Gets called on initial true binding on switch checked
}
每次加载页面时都会调用onSwitchModule,而item.active在任何项目上都是true,如何处理?
注意:Nativescript中的初学者
答案 0 :(得分:0)
我遇到了类似的问题:从API加载设置数据,并为{I}设置的值checked
事件触发 - 在我的情况下不可取。我没有看到防止事件触发初始绑定的好方法,所以我决定忽略事件,直到我知道它们是实际使用开关的用户的合法事件。
我通过使用属性switchReady
来跟踪您何时开始识别更改事件。此模式还会禁用切换,直到您准备开始接受更改为止。这使用了Switch的isEnabled
属性,请参阅docs here。
标记
<Switch [checked]="currentSettings.pushTurnedOn" [isEnabled]="switchReady" (checkedChange)="onPushSettingChange($event)" row="0" col="1"></Switch>
组件
export class SettingsComponent implements OnInit {
currentSettings: Settings = new Settings(false)
switchReady: boolean = false
ngOnInit() {
this.getCurrentSettings()
}
public onPushSettingChange(args) {
let settingSwitch = <Switch>args.object
if (settingSwitch.isEnabled) {
// do something with the event/change
} else {
// we aren't ready to accept changes, do nothing with this change
return
}
}
getCurrentSettings() {
this.settingsService.loadCurrentSettings().subscribe(
() => {
this.currentSettings = this.settingsService.currentSettings
// we've applied our api change via data binding, it's okay to accept switch events now
this.switchReady = true
},
err => alert('There was a problem retrieving your settings.')
)
}
}
答案 1 :(得分:0)
我为克服此问题所做的工作是,我观看tap
事件而不是checkedChange
:
<Switch (tap)="switchClicked" [checked]="item.active"></Switch>
在回调中,您可以从bindingContext
获取当前项目:
function switchClicked(args) {
const item = args.object.bindingContext.item;
}