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!
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 tongModel
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 aPATCH
, this meant that every other client would automatically trigger aPATCH
when the data bound to the toggle changed.We used:
<ion-toggle [ngModel]="isToggled" (ngModelChange)="notifyAndUpdateIsToggled()"></ion-toggle>
to get around this