Reputation: 678
I have a very simple question , i am building an app where i have a settings page with a toggle input for a user to turn on and off some alerts . My question is how do i save the toggle value so as when someone closes the app or navigate to another page the toggle status should not get lost and the current toggle should be reflected in html. At the moment i am using cordova-sqlite-storage plugin to store the toggle value .
Page.html
<ion-item>
<ion-label>300 Units</ion-label>
<ion-toggle [(ngModel)]="AlertOn200" [checked]="toggleStatus" (ionChange)="Change_Toggle_on_200();"></ion-toggle>
</ion-item>
Page.ts
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';
@Component({
selector: 'page-page2',
templateUrl: 'page2.html'
})
export class Page2 {
AlertOn200:any;
toggleStatus:any;
val:any;
constructor(public storage: Storage) {
storage.ready().then(() => {
// get a key/value pair
storage.get('toggleStatus').then((val) => {
this.val=val;
console.log('Status = ', val);
})
});
}
Change_Toggle_on_200() {
if(this.AlertOn200== true){
this.storage.set('toggleStatus','true');
console.log("isAlertOn200 = "+this.toggleStatus);
}
else{
this.storage.set('toggleStatus','false');
console.log("isAlertOn200 = "+this.toggleStatus);
}
}
Upvotes: 1
Views: 1333
Reputation: 529
On storage.ready()
you should set the AlertOn200
and/or toggleStatus
property in your class instead of the val
property. This should set the toggle to the value in your storage.
EDIT: I've added some code below which I've tested and works. The ion-toggle gets its initial value set by the value in the storage, if you manually toggle the ion-toggle, the value in storage changes.
I would suggest removing the [checked]
binding in the ion-toggle component and set the model of the toggle to toggleStatus
, like so:
<ion-toggle [(ngModel)]="toggleStatus" (ionChange)="Change_Toggle_on_200();"></ion-toggle>
If you then implement the following class:
export class Page1 {
toggleStatus: any;
constructor(public navCtrl: NavController, public storage: Storage) {
storage.ready().then(() => {
storage.get('toggleStatus').then((val) => {
console.log(`Setting status from storage to '${this.toggleStatus}'`);
this.toggleStatus = val; // <-- Just set this.toggleStatus to the value from storage, this will make the ion-toggle change value from default to value from storage
})
});
}
Change_Toggle_on_200() {
console.log(`changing toggleStatus to '${this.toggleStatus}'`);
this.storage.set('toggleStatus', this.toggleStatus); // <-- note we can just set the current value of this.toggleStatus as this changes with the toggle
}
}
Upvotes: 3