Ionic4 Alert Dynamic Checkboxes

Hi, everyone!

I am migrating from Ionic V3 to V4. I used to have an alert with dynamic checkboxes. The code used to be like this:

let alert = this.alertCtrl.create ();
alert.setTitle (this.alertTitle);
for (var i = 0; i < this.myArray.length; i ++) {
  alert.addInput ({
    type: 'checkbox',
    label: alert,
    value: '' + i,
    checked: false
  });
}

alert.addButton 'cancel');
alert.addButton ({
  text: 'ok',
  handler: data => {
    console.log ('hi')
  }
});
alert.present ();

But now I can initialize let alert = this.alertCtrl.create (); but I can’t access any method like alert.addInput ().

Is there any other way of doing this?

Maybe something like this:

export class HomePage {
  myArray = [];
  alertTitle = '';
  myInputs = [];

  constructor(public alertController: AlertController) {
    this.myInputs = this.createInputs();
  }

  createInputs() {
    const theNewInputs = [];
    for (let i = 0; i < this.myArray.length; i++) {
      theNewInputs.push(
        {
          type: 'checkbox',
          label: alert,
          value: '' + i,
          checked: false
        }
      );
    }
    return theNewInputs;
  }

  async presentAlertCheckbox() {
    const alert = await this.alertController.create({
      header: this.alertTitle,
      inputs: this.myInputs,
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            console.log('Confirm Cancel');
          }
        }, {
          text: 'Ok',
          handler: () => {
            console.log('Confirm Ok');
          }
        }
      ]
    });

    await alert.present();
  }
}

2 Likes

That’s actually a great idea. Will try.

Forgot mention, I haven’t tested the code :wink:

Great It Is Working…