Sunday, 1 October 2017

How to Implement Alert in ionic 2, ionic3 using AlertController.

Alerts are Used to Show important Information to User, it can also be used to require them to make a decision or response from user. Alerts are nothing but type of "floating" modals that appear on top of the app's Content. They are mainly used to give or take information from the user like accepting yes or no, password verification, Information regarding task status etc. Alerts in Ionic are flexible and can also be customized. In this post we learn how to show different types of alerts and how to controll and retrieve data from user when he selects or inputs a value. Note: This post assumes that you already have a working ionic project. Alerts in ionic are of 5 Types: Basic Alerts Prompt Alerts Confirmation Alerts Radio Alerts Checkbox Alerts We will now look in to all the alert types in ionic framework. first lets see how to implement "Basic Alerts", Basic Alerts : Basic Alerts are used to notify the user about any information regarding tasks or processes in the app, a situation where the app requires acknowledgement from user, or a confirmation to the user that an action was done successfully or not.

Copy & Paste the below ts code to your components/pages ts file.


import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-alert-controller',
  templateUrl: 'alert-controller.html',
})
export class AlertControllerPage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad AlertControllerPage');
  }

  showBasicAlert() {
    let basicAlert = this.alertCtrl.create({
      title: 'IonicSync.com',
      subTitle: 'A Site where you get to know "How to Implement the basic things" about ionicframework.',
      buttons: ['OK']
    });
    basicAlert.present();
  }

}
Explanation: first we should import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showBasicAlert is the method called when you click on basic alert button. basicAlert.present() initiates the alert and displays it on top of you app's content. Prompt Alerts Prompts gives user a way to input information or data in to the alertbox. Prompt alerts can also be used to ask the user for a password to verify the user, before moving forward in an application’s flow.

Copy & Paste the below showPromptAlert method code to your components/pages ts file.


 showPromptAlert() {
 let promptAlert = this.alertCtrl.create({
   title: 'Register on ionicSync.com',
   message: "Enter a name which will be user as UserName ",
   inputs: [
     {
       name: 'title',
       placeholder: 'Title'
     },
   ],
   buttons: [
     {
       text: 'Cancel',
       handler: data => {
         console.log('Cancel clicked');
       }
     },
     {
       text: 'Submit',
       handler: data => {
         console.log('Saved clicked');
         console.log("Data Entered",data)
       }
     }
   ]
 });
 promptAlert.present();
  }
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showPromptAlert is the method called when you click on prompt alert button. promptAlert.present() initiates the alert and displays it on top of you app's content. when the user clicks on submit button, its handler has the data the user entered in the input field. Confirmation Alerts Confirmation Alerts are used, when it is mandatory that the user should confirm a particular choice before progressing forward in the app. An example of the Confirmation Alert is checking to make sure that the user wants to delete or remove a contact from their address book.

Copy & Paste the below showConfirmAlert method ts code to your components/pages ts file.


showConfirmAlert() {
    let confirmAlert = this.alertCtrl.create({
      title: 'Are you Sure you want to delete this contact?',
      message: 'Do you agree to use this lightsaber to do good across the intergalactic galaxy?',
      buttons: [
        {
          text: 'Disagree',
          handler: () => {
            console.log('Disagree clicked');
          }
        },
        {
          text: 'Agree',
          handler: () => {
            console.log('Agree clicked');
            // Your Imagination should go here
          }
        }
      ]
    });
    confirmAlert.present();
  }
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showConfirmAlert is the method called when you click on confirm alert button. confirmAlert.present() initiates the alert and displays it on top of you app's content. when the user clicks on Agree button, the code to delete the contact goes inside agree handler. Radio Alerts Radio Alerts are similar to that of Confirmation Alert, but it uses the Radio component to offer several choices for user. A set of options is provided to the user, but user can only select one option.

Copy & Paste the below showRadioAlert method ts code to your components/pages ts file.


  showRadioAlert () {
    let radioAlert = this.alertCtrl.create();
    radioAlert.setTitle('Your Order');

    radioAlert.addInput({
      type: 'radio',
      label: 'Burger',
      value: 'burger',
      checked: true
    })
 radioAlert.addInput({
      type: 'radio',
      label: 'Pizza',
      value: 'pizza',
      checked: false
    })
 radioAlert.addInput({
      type: 'radio',
      label: 'Coffee',
      value: 'coffee',
      checked: false
    })
 radioAlert.addInput({
      type: 'radio ',
      label: 'Noodles',
      value: 'noodles',
      checked: false
    });

    radioAlert.addButton('Cancel');
    radioAlert.addButton({
      text: 'OK',
      handler: data => {
   console.log("Ordered",data)
        this.testRadioOpen = false;
        this.testRadioResult = data;
      }
    });
    radioAlert.present();
  }
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showRadioAlert is the method called when you click on radio alert button. radioAlert.present() initiates the alert and displays it on top of you app's content. when the user selects any one of the radio option's and click on ok, he selected option data is send to radiobutton handler. Checkbox Checkbox Alerts are similar to that of Confirmation Alert, but use the Checkbox component to offer multiple choices. They offer the user a set of options to choose.

Copy & Paste the below showRadioAlert method ts code to your components/pages ts file.


  showCheckboxAlert() {
    let checkboxAlert = this.alertCtrl.create();
    checkboxAlert.setTitle('Which planets have you visited?');

    checkboxAlert.addInput({
      type: 'checkbox',
      label: 'Alderaan',
      value: 'value1',
      checked: true
    });

    checkboxAlert.addInput({
      type: 'checkbox',
      label: 'Bespin',
      value: 'value2'
    });

    checkboxAlert.addButton('Cancel');
    checkboxAlert.addButton({
      text: 'Okay',
      handler: data => {
        console.log('Checkbox data:', data);
        this.testCheckboxOpen = false;
        this.testCheckboxResult = data;
      }
    });
    checkboxAlert.present();
 this.testCheckboxOpen = true;
  }
 
Explanation: import AlertController to implement the alert in our page and then add parameter "alertCtrl" as public in your page's constructor. showCheckboxAlert is the method called when you click on checkbox alert button. checkboxAlert.present() initiates the alert and displays it on top of you app's content. when the user selects one or multiple checkbox option's and click on ok, he selected option data is send to radiobutton handler. Finally modify the your components html file as below.

Copy & Paste the below code to your components html file.



<ion-header>

  <ion-navbar>
    <ion-title>Alert Controller</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>

  <ion-item-group>
    <ion-item-divider color="light">Basic Alerts</ion-item-divider>
       <button ion-button full (click)="showBasicAlert()">Basic</button>    
    <ion-item-divider color="light">Prompt Alerts</ion-item-divider>
       <button ion-button full (click)="showPromptAlert()">Prompt</button>    
    <ion-item-divider color="light">Confirmation Alerts</ion-item-divider>
       <button ion-button full (click)="showConfirmAlert()">Confirmation</button>    
    <ion-item-divider color="light">Radio Alerts</ion-item-divider>
       <button ion-button full (click)="showRadioAlert()">Radio</button>    
    <ion-item-divider color="light">Checkbox</ion-item-divider>
       <button ion-button full (click)="showCheckboxAlert()">Checkbox</button>    
  </ion-item-group>
</ion-content>
<ion-footer >
  <ion-toolbar>
    <ion-title>IonicSync.com</ion-title>
  </ion-toolbar>
</ion-footer>

0 comments:

Post a Comment