Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from input in Ionic 4 alert

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?

like image 908
Andi Avatar asked Apr 05 '19 17:04

Andi


2 Answers

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();
like image 64
Ira Watt Avatar answered Nov 03 '22 06:11

Ira Watt


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

like image 29
bene-we Avatar answered Nov 03 '22 07:11

bene-we