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!
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
You can use $event
in ionChange
.
View:
<ion-toggle (ionChange)="notify($event)"></ion-toggle>
Controller:
notify(event) {
console.log(event.checked);
}
There are 2 ways of checking.
First one is like @Chathuranga Silva suggested
html
<ion-toggle (ionChange)="notify($event)"></ion-toggle>
ts
notify(event: any) { console.log("toggled: "+event.target.checked); }
Second one would be something like this:
html
<ion-toggle (ionChange)="notify()" [checked]="isToggled"></ion-toggle>
ts
var isToggled: boolean = true;
notify() {
console.log("toggled: "+ this.isToggled);
}
Which one you pick is up to you, I'd recommend the second one since it will be easier to manipulate the toggle in the constructor/onInit, and easier using this value outside the notify()
method.
You can use $event in ionChange.
View:
<ion-toggle (ionChange)="onChange($event)"></ion-toggle>
Controller:
onChange(ev) {
console.log(ev.target.checked);
}