Using variable from storage to check ion-checkbox on app start!


#1

Hello there,

I’m trying to learn more about ionic, starting with the basics by creating a list of checkboxes. It’s a reading app and the user will be able to select which content he does and doesn’t want to see. Right now, this is the code for the checkbox list:

<ion-content padding>
  <ion-list>
    <ion-item>
      <ion-label>Jon Snow</ion-label>
      <ion-checkbox [(ngModel)]="cucumber" (ionChange)="updateChecklist()"></ion-checkbox>
    </ion-item>
    <ion-item>
      <ion-label>Daenerys Targaryen</ion-label>
      <ion-checkbox color="dark" checked="true"></ion-checkbox>
    </ion-item>
  </ion-list>
</ion-content>

Whenever the user click on “Jon Snow”, my .ts does:

  checklist: boolean = false;
  var:string;

  updateChecklist() {
    this.storage.set('name', 'John').then(() => {
      if (this.checklist){
        this.checklist = false;
        this.storage.set('state', 'false');
      } else {
        this.checklist = true;
        this.storage.set('state', 'true');
      }

      this.storage.get('state').then((val) => {
        this.var = val;
        console.log(this.var);
      });
    });
  }

What I want to do is to set Daenerys Targaryen:

    <ion-item>
      <ion-label>Daenerys Targaryen</ion-label>
      <ion-checkbox color="dark" checked="true"></ion-checkbox>
    </ion-item>

Based on the ‘state’ on storage.

What I tried to do is create a second function:

  getState (){
    return this.storage.get ('state');
  }

and use it like this:

    <ion-item>
      <ion-label>Daenerys Targaryen</ion-label>
      <ion-checkbox color="dark" checked="getState ()"></ion-checkbox>
    </ion-item>

But that’s not working, how can I get a value from storage and use it to check my checkboxes whenever I go to this pages or on the app start?

When I click on Jon snow my console is:

console.log: true and console.log: false, etc.

Thank you!


#2

I think it’s generally a mistake to have both [(ngModel)] and (ionChange): I only use one or the other, as having both opens a door to bugs when they fight.

These three lines make no sense and should go away:

      this.storage.get('state').then((val) => {
        this.var = val;
        console.log(this.var);
      });

This is returning a Promise, so you would have to use the AsyncPipe to do it this way, but I wouldn’t recommend doing that, as it’s very inefficient. You have a checklist property in the controller already. Use that:

constructor(private _storage: Storage) {
  _storage.get('state').then(state => this.checklist = state);
}

<ion-checkbox [checked]="checklist">

#3

It’s just a copy and paste from the ionic’s documentation, you can find it here: https://ionicframework.com/docs/api/components/checkbox/Checkbox/ under “Advanced”.

This is was just a test, but thank you anyway.

Thank you, I’m going to try that!