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. 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 .
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.
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
You can use $event
in ionChange
.
View:
<ion-toggle (ionChange)="notify($event)"></ion-toggle>
Controller:
notify(event) {
console.log(event.checked);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With