Toggle (change) event


#1

I have a listener attached to the (change) event on a toggle component. When the user taps to switch the toggle, the change event fires and a ngrx store event is then dispatched to update the model. When the model changes the [checked] value of the toggle, the change event fires again.

Is there a way to listen to an event ONLY when the user has tapped the switch and it finishes the toggle animation?


Toggle triggers ionChange when opening page
Ion-toggle issue
Ion-toggle ionChange fires on page load
How do I prevent an ion-checkbox from being checked?
#2

Hmm, could you provide a demo of this in a codepen?

http://codepen.io/tlancina/pen/EPBdVE/


#4

@jasonwaters I take that back. It wasn’t consistent. I found that using (click) and sending in the model value was inconsistent. It wasn’t always sending in the right toggle state. So sometimes the toggle is in true it would send false to the function i’m calling. I guess the ngModel was being updated after the function call is fired. (occasionally).

Did you find a solution for this ?


#5

I think the solution is to change how ion-toggle works so that it only fires change events if the user has clicked it and the animation has completed. It doesn’t make sense to fire a change event if the model object changes value due to some other reason.

My workaround was to add an if block like this inside the change handler:

handleToggleChange(evt) {
   if(evt.checked !== myModel.active) {
      //dispatch ngrx store event here, which ends up setting myModel.active via observables.
   }
}

I’m not happy with this solution, but it works in my use case.


Ion-toggle (ionChange) triggered
#6

Thank you for this suggestion. I added to it to work with my situation, in which the value backing the toggle cannot be directly modified by the time the change event fires (for example, a confirm dialog might be popped or an API call might need to succeed). I tried a bunch of things, and settled on your idea.

What I discovered is that the event parameter is actually the Toggle itself. So if you need to back out the change, you can assign to its checked property inside the change handler. This will realign the toggle widget’s checked state with that of the backing component, so even if that causes another change event to fire, your guard will protect against popping the confirm dialog twice.