Search code examples
ionic-frameworkionic2alerthybrid-mobile-app

How do I set text field for alert message in the alert dialog in Ionic 2?


I am getting a push notification using Firebase and showing it in alert box. Now I want to display the message i received in a text field so that user can edit the message.I also want to output the message in console.

pushObject.on('notification').subscribe((notification: any) => {
  if (notification.additionalData.foreground) {
    let youralert = this.alertCtrl.create({
      title: 'New Push notification',
      message: notification.message,
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
           console.log('Cancel clicked');
          }
        },
        {
          text: 'Okay',
          handler: () => {
            console.log('Okay clicked');
          }
        }
      ]
    });

Solution

  • There's a inputs property on the Alert interfacce, it works pretty much like the buttons. It's an array of objects and you have a input value property to set the desired value.

    Since i don't know where you want to log you value and if it's the value that has come from the server or the edited value, i'll show both.

    pushObject.on('notification').subscribe((notification: any) => {
      if (notification.additionalData.foreground) {
        console.log('push message', notification.message);
        let youralert = this.alertCtrl.create({
          title: 'New Push notification',
          inputs: [{
            placeholder: 'Your placeholder..',
            type: 'text',
            name: 'yourInputName, // Name to get it in your handler callback
            value: notification.message
          }],
          message: notification.message,
          buttons: [
            {
              text: 'Cancel',
              role: 'cancel',
              handler: () => {
               console.log('Cancel clicked');
              }
            },
            {
              text: 'Okay',
              // you'll need to get the input data, so pass a parameter to the callback
              handler: (data) => {
                // here's the value user has edited in the input
                console.log('Edited message', data.yourInputName);
                console.log('Okay clicked');
              }
            }
          ]
        });
    

    Hope this helps