Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic2 ion-toggle get value on ionChange

I have this toggle here:

<ion-toggle (ionChange)="notify(value)"></ion-toggle>

When I click this I want to call the method notify passing the toggle value by parameter. How I can get the toggle value?

Thank you!

like image 441
bbcbreno Avatar asked Nov 21 '16 21:11

bbcbreno


People also ask

How do you get toggle value in ionic?

Just like you can see in Ionic2 Docs - Toggle, a better way to do that would be to bind the toggle to a property from your component by using ngModel. This way, you don't need to send the value because it's already a property from your component and you can always get the value by using this. isToggled .

How do you toggle with ions?

Toggles change the state of a single option. Toggles can be switched on or off by pressing or swiping them. They can also be checked programmatically by setting the checked property.


2 Answers

Just like you can see in Ionic2 Docs - Toggle, a better way to do that would be to bind the toggle to a property from your component by using ngModel.

Component code:

public isToggled: boolean;

// ...

constructor(...) {
  this.isToggled = false;
}

public notify() {
  console.log("Toggled: "+ this.isToggled); 
}

View:

<ion-toggle [(ngModel)]="isToggled" (ionChange)="notify()"></ion-toggle>

This way, you don't need to send the value because it's already a property from your component and you can always get the value by using this.isToggled.

UPDATE

Just like @GFoley83 mentioned on his comment:

Be very careful with ionChange when it's bound directly to ngModel. The notify method will get called when the value bound to ngModel changes, either from the view via someone clicking the toggle or in your component via code e.g. when you do a fresh GET call. I had an issue recently whereby clicking the toggle triggered a PATCH, this meant that every other client would automatically trigger a PATCH when the data bound to the toggle changed.

We used: <ion-toggle [ngModel]="isToggled" (ngModelChange)="notifyAndUpdateIsToggled()"></ion-toggle> to get around this

like image 99
sebaferreras Avatar answered Sep 17 '22 14:09

sebaferreras


You can use $event in ionChange.

View:

<ion-toggle (ionChange)="notify($event)"></ion-toggle>

Controller:

notify(event) {
   console.log(event.checked);   
}
like image 33
Jaydeep Kataria Avatar answered Sep 20 '22 14:09

Jaydeep Kataria