bbcbreno
bbcbreno

Reputation: 378

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!

Upvotes: 16

Views: 45640

Answers (5)

Hammad Ahmad
Hammad Ahmad

Reputation: 204

You can use $event in ionChange.

View:

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

Controller:

onChange(ev) {
   console.log(ev.target.checked);   
}

Upvotes: 1

Jaydeep Kataria
Jaydeep Kataria

Reputation: 867

You can use $event in ionChange.

View:

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

Controller:

notify(event) {
   console.log(event.checked);   
}

Upvotes: 18

sebaferreras
sebaferreras

Reputation: 44669

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

Upvotes: 37

CNB
CNB

Reputation: 315

Use this

<ion-toggle id="availabilityButton" [(ngModel)]="setOffOrnot"
(ionChange)="setAvailability()"></ion-toggle>

setAvailability(e) {
  this.setOffOrnot = ...
}

Upvotes: -1

Ivar Reukers
Ivar Reukers

Reputation: 7719

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.

Upvotes: 5

Related Questions