Nativescript Switch 防止在初始绑定时触发更改事件

Niy*_*yaz 5 nativescript angular2-nativescript

嗨,我的模板如下所示

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

我的控制器是

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

}

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

每次页面加载时 onSwitchModule 都会被调用,item.active 在任何项目上为 true,如何处理?

注意:Nativescript 初学者

set*_*ine 0

我遇到了类似的问题:从 API 加载设置数据,并让checked我从 api 设置的值触发事件——这在我的情况下是不可取的。我没有找到阻止事件在初始绑定上触发的好方法,因此我决定简单地忽略事件,直到我知道它们是来自实际使用开关的用户的合法事件。

我通过使用一个属性switchReady来跟踪您何时想要开始识别更改事件来做到这一点。此模式还会使切换保持禁用状态,直到您准备好开始接受更改为止。这利用了 Switch 的isEnabled属性,请参阅此处的文档

标记

<Switch [checked]="currentSettings.pushTurnedOn" [isEnabled]="switchReady" (checkedChange)="onPushSettingChange($event)" row="0" col="1"></Switch>
Run Code Online (Sandbox Code Playgroud)

成分

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.')
    )
  }
}
Run Code Online (Sandbox Code Playgroud)