Lisa
Lisa

Reputation: 675

restore the toggle button status in ionic2

On ionChange I am checking some condition, if condtion is set to false I want to restore the toggle buttons previous position. Here is the relevant code

changeStatus(item) {
    if(this.mqttservice.response) {
        //doing smthg
    } 
    else {
        item.status =!item.status;
        //bring back the toggle to previous position
    }
}
<ion-toggle  [(ngModel)]="item.status" (ionChange)="changeStatus(item);" checked="false">

The issue is since I am changing the state changeStatus() is called indefinitely. How do I prevent this and restore toggle button previous position on else condition?

Upvotes: 2

Views: 702

Answers (1)

Patrick
Patrick

Reputation: 17973

The [()] syntax means you are getting updates and posting updates when the variable changes. Since you are using (ionChange) you can use the [] syntax instead, which means it only gets updates (but won't post them)

<ion-toggle [ngModel]="item.status" (ionChange)="changeStatus($event, item);">

Since the toggle button changes its state, in order for it to "change back" you need to toggle the value back and forth. You can solve this by setting the value and then if it fails, trigger a change "in the future" by adding a setTimeout.

public changeStatus(event: boolean, item: Item) {
  item.status = event;
  if (allGood) {
    // do something
  }
  else {
    // revert to old value
    setTimeout(() => { item.status = !event; });
  }
}

Upvotes: 1

Related Questions