Hello there,
So I am having trouble working with defining operations dynamically for the button handlers of an alert. The aim is to iterate over an array to create the alert buttons and to pass the respective information to the button handler when it gets called.
If this is not achievable can the click event be passed in the handler function carrying information that will enable us to distinguish what button was pressed?
I have attached some code, which does not work, but showcases the “issue”.
Any help greatly appreciated.
presentAlert() {
var aletInfo = {
title: "Hello",
body: "This is a greeting",
buttons: [
{
text: "Say hi back",
action: "returnGreeting"
},
{
text: "Do nothing",
action: "ingnoreGreeting"
},
{
text: "Start a fight",
action: "reactToGreeting"
},
]
}
var alertBody = {
header: alertInfo.title,
message: alertInfo.body,
buttons: []
};
for (var i = 0; i < alertInfo.buttons.length; i++) {
var button: any = {};
button.text = alertInfo.buttons[i].text
button.handler = (i)=>{
processGreeting(i, aletInfo)
}
// i is out of context when it is finally called
alertBody.buttons.push(button)
}
let alert = await this.alertCtrl.create(alertBody);
alert.present();
}
processGreeting(i) {
var action = aletInfo.buttons[i].action
if(action === "returnGreeting"){
// Do something
} else {
// Do something else
}
}