Creating an object based on a function’s parameter

Issue

I’m trying to create an object, a cancel button, based on a parameter given to a function. See code below. Now I know the button inside the if statement is out of scope, but I would just like to know how to achieve what I want to do.

  async presentAlert(header: string, message: string, cancel?: boolean) {
    if (cancel) {
      const cancelButton  {
        text: 'Cancel',
        role: 'cancel',
        cssClass: 'secondary',
      };
    }

    const alert  await this.alertController.create({
      cssClass: 'my-custom-class',
      header: header,
      message: message,
      buttons: [
        {
          text: 'OK',
          handler: () > {
            this.goBack();
          },
        },
        //The button I made based on the parameter
        cancelButton,
      ],
    });

    await alert.present();
  }

Solution

Create the array of buttons, push the delete button into it, then pass the array to the alert controller.

async presentAlert(header: string, message: string, cancel?: boolean) {
const myButtons  [
    {
      text: 'OK',
      handler: () > {
        this.goBack();
      }
    }
];

if (cancel) {
  myButtons.push({
    text: 'Cancel',
    role: 'cancel',
    cssClass: 'secondary',
  });
}

const alert  await this.alertController.create({
  cssClass: 'my-custom-class',
  header: header,
  message: message,
  buttons: myButtons ,
});

await alert.present();
}

Answered By – spots

Leave a Comment