Search code examples
javascripttypescriptionic-frameworkhandle

Two way databinding on ionic component "alertcontroller"


Is it possible to have two way data binding in an ionic alertcontroller ?, I have tried different ways and I have not succeeded, try adding a handler to the text input but I could not, I wanted to know if there is any function that takes the input changes of the alertcontroller. Help please.

let prompt = this.alertCtrl.create({
          title: 'VALORES DE LA ENTRADA',
          message: "INGRESE EL COSTO, EL IVA, EL DESCUENDO Y LA CANTIDAD",
          inputs: [
            {
              name: 'costo',
              label: 'COSTO: ',
              placeholder: 'COSTO',
              value: (productData[0].costo).toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
            },
            {
              name: 'iva',
              label: 'IVA: ',
              placeholder: 'IVA',
              value: iva
            },
            {
              name: 'descuento',
              placeholder: 'DESCUENTO',
              value: descuento
            },
            {
              name: 'cantidad',
              placeholder: 'CANTIDAD',
              value: cantidad
            }
          ],
          buttons: [
            {
              text: 'Cancelar',
              handler: data => {
                console.log('Cancel clicked');
              }
            },
            {
              text: 'Aceptar',
              handler: data => {
                costo = data.costo;
                iva = ((costo) - (descuento))* 0.16;
                descuento = data.descuento;
                cantidad = data.cantidad;
                cantidadEq = cantidad * this.valorEq;
                var costoTotal = costo * cantidad;
                var total = (costoTotal + (iva*cantidad)) - descuento;
              }
            }
          ]
        });
        prompt.present();

Solution

  • There is no easy way to have either two-way data binding or even change handlers on inputs in AlertController. The AlertController is intended for simple use cases.

    According to AlertController docs:

    If you require a complex form UI which doesn't fit within the guidelines of an alert then we recommend building the form within a modal instead:

    This can be achieved by something like:

    let formModal = this.modalCtrl.create(MyCustomFormComponent);
    

    where MyCustomFormComponent is a component with form and two-way biding.

    And in this answer you can find example how to get data back from modal: Ionic 2 - Get data back from modal