Ionic 2 Toggle event preventdefault


#1

I have a Toggle switch. I want not to check or uncheck the toggle at first which is why I need to use preventDefault.

I have used ionChange() instead of click() event handler. But with ionChange handler, the cancelable or defaultPrevented property does not exists. So, it raises error that preventDefault() is not a function. However, with simple click handler, it does not raise any error but does not work either. I have also tried with stopPropagation().

Here is the code.

HTML:

<ion-item>
            <ion-toggle [(ngModel)]="appliance.state" (ionChange)="applianceChange($event)"></ion-toggle>
</ion-item>

TS:

import { Component, EventEmitter } from '@angular/core';

@Component({
  selector: 'appliances',
  templateUrl: 'appliances.html'
})
export class ApplianceModule {
  constructor(){}

 applianceChange(event: Event){
   event.preventDefault(); 
 }
}

#2

Maybe there isn’t any default event to prevent… Not sure.

But there is another approach to this if you don’t wanna use click event. You can replace applicance.state with a different property that has get/set methods. For example:

<ion-toggle [(ngModel)]="applianceState"></ion-toggle>
...
... class BlahModule {
...

appliance = {
  ...
  state: true
  ...
};

get applianceState() { return this.appliance.state }

set applianceState(state: boolean) {

  // some logic here
  this.appliance.state = state; // or w.e other value you wanna use here

}

...
}


#3

I have what I believe is a similar situation, and here’s how I approached it:

<ion-toggle [checked]="appliance.state"
 (ionChange)="applianceChange($event, appliance)">
applianceChange(ctl: Toggle, app: Appliance): void {
  if (ctl.checked === app.state) {
    return;
  }

  // do further things that may or may not change app.state
}