Search code examples
ionic-frameworkionic2ionic2-select

is there a way to listen to model changes in ionic 2 and only then set the values back to storage?


I have an ionic 2 class:

export class SettingsPage {

  public num = 2;
  public num1 = 3;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              public storage: Storage) {
    storage.ready().then(() => {

      // Or to get a key/value pair
      storage.get('num').then((val) => {
        if (val != null) {
          this.num = val;
        } else {
          this.num = 2;
        }

      })
    });
  }

what is the best practice? is there a way to listen to any change in any of the variables (num, num1) and then set the value back to storage to persist it?


Solution

  • The question is not related to Ionic but TypeScript.

    You can define property with get & set methods like:

    class YouClass {
        private _num: boolean = false;
    
        get num(): boolean {
            return this._num;
        }
    
        set num(value: boolean) {
            this._num = value;
    
            // Here you can save the value in the storage ...
            this.storage.set('num', value);
        }
    }
    

    And in set you can do what ever you want. Including saving to storage.