27

As of today the Ionic 4 documentation on ion-alert contains an example how to add a text input to an alert, like this:

const alert = await this.alertController.create({
  inputs: [
    {
      name: 'name1',
      type: 'text'
    },

But I can not find out how to access the value from the name1 text input, for example in the button handlers.

Do I have to use something like document.getElementById or is there a more Ionic/Angular-style way?

pppery
  • 3,731
  • 22
  • 33
  • 46
Andi
  • 3,234
  • 4
  • 32
  • 37

3 Answers3

50

you can have a button that on the close of the alert can handle the data.

const alert = await this.alertController.create({
    inputs: [
    {
        name: 'name1',
        type: 'text'
    }],    
    buttons: [
        {
            text: 'Cancel',
            role: 'cancel',
            cssClass: 'secondary',
            handler: () => {
                console.log('Confirm Cancel');
            }
        }, 
        {
            text: 'Ok',
            handler: (alertData) => { //takes the data 
                console.log(alertData.name1);
            }
        }
    ]
});
await alert.present();
Gedeon Mutshipayi
  • 2,871
  • 3
  • 21
  • 42
Ira Watt
  • 2,095
  • 2
  • 15
  • 24
11

Actually this can be shortened to:

const alert = await this.alertController.create({
    header: 'Prompt!',
    inputs: [
        {
            name: 'input1',
            type: 'text',
            placeholder: 'Please enter text'
        }
    ],
    buttons: [
        {
            text: 'Cancel',
            role: 'cancel',
            cssClass: 'secondary',
            handler: () => {
                console.log('Confirm Cancel');
            }
        }, 
        {
            text: 'Ok',
            handler: (alertData) => {
                console.log(alertData.input1);
            }
        }
    ]
});

While the parameter `alertData` just contains the inputs with their values:

alertData in console

Gedeon Mutshipayi
  • 2,871
  • 3
  • 21
  • 42
bene-we
  • 761
  • 11
  • 23
1

As an alternative to the other answers (and to avoid the use of an inline handler), the input values are also available in the result of onDidDismiss():

const alert = await this.alertController.create({
    header   : 'Test',
    buttons: ['OK'],
    inputs: [
        {
            placeholder: 'Name',
            name: 'name',
        },
    ],
});

await alert.present();

const result = await alert.onDidDismiss();

console.log(result);
// {data: {name:'${your input value}'}, role: undefined}
chris
  • 3,019
  • 23
  • 21