0

Hello i try to open an alert when a ion-toggle is clicked to ask if the user is sure to execute this action but the toogle change before the alert is opened because of the asyn... Could someone explain me how to handle the toggle action with the alert? Thanks ! U can see my code here :

Html :

<ion-toggle slot="end" (ngModelChange)="onToggleAppareil(appareil)" [(ngModel)]="appareil.status"></ion-toggle> 

TS function :

public async onToggleAppareil(appareil:any){
      if(appareil.status == true){
      let alert = await this.alertCtl.create(
        {
          header: 'Voulez vous continuer ?',
          message:'Cette action va éteindre l\'appareil sélectionné',
          buttons:[
            {
              text:'Annuler',
              handler: ()=>{
                appareil.status = true;
              },
              role:'cancel',
              cssClass:'secondary'
            },
            {
              text:'Confirmer',
              handler: ()=>{
                appareil.status = false;
              }
            }
          ]
        }
      );
       alert.present();
    }
  }

(This alert is displayed only if the user want to disabled the toggle but it does true => false if canceled => true cause of the async)

Dralyx
  • 1
  • 1

1 Answers1

0

You should use a click event to trigger your function

(click)="onToggleAppareil(appareil)"

ngModelChange fires when the model changes, read more about it here: https://stackoverflow.com/a/45075106/1934484

Extra

public async onToggleAppareil(appareil: { status: boolean }) {
  if (appareil.status) { // thruthy values
      let alert = await this.alertCtl.create(
        {
          header: 'Voulez vous continuer ?',
          message:'Cette action va éteindre l\'appareil sélectionné',
          buttons:[
            {
              text:'Annuler', // unnecessary to set to true because it is already true
              role:'cancel',
              cssClass:'secondary'
            },
            {
              text:'Confirmer',
              handler: () => appareil.status = false;
            }
          ]
        }
      );

      await alert.present(); // added await like stated in docs
    }
  }
Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45