Saturday, 24 March 2018

How to Make a HTTP Call and Fetch Data in Ionic 2 and 3

In this Post we are going to see on, how to make a http request/call and fetch the response data in ionic 2 & 3 framework.

This post assumes that you already have the ionic project created and running.

lets create a page in our project to implement the HTTP Call request.Now, Execute the below command to create home page.

ionic generate page home

Now, navigate to the page folder that you just created, ie navigate to src/pages/home directory.

Open home.ts and modify your code as shown below.

Modify home.ts file

home.ts



import { Component } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { NavController } from 'ionic-angular';
import 'rxjs/add/operator/map';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  public items: any;
  constructor(public navCtrl: NavController, public http: Http) {
  
  }

  ionViewDidLoad(){
    console.log("View Did Load")
  }

  CallApiWithGet(){
    this.http.get('https://www.reddit.com/r/gifs/new/.json?limit=10')
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);
        this.items = data.data.children;
    });
  }


  CallApiWithPost(){
    let headers = new Headers();
    headers.append('Content-Type,'application/json');
    
    let body = {
      message: "Hi there my friend !!"
    }

    // Please change the url.

    this.http.post('http://localhost:8040/api/test',JSON.stringify(body),{headers: headers})
    .map(res => res.json())
    .subscribe(data => {
        console.log(data);
    });
  }
}

Above Code Expalanation

First we must import http & map operator for the http request to work properly without any errors.

import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

Next, inject Http into the home pages constructor.

We have CallApiWithGet() function, which calls a get request. we use get to retrieve the JSON data from the URL provided. Here we also have map & subscribe , to explaing in short, the http.get returns the result in the form of an Observable, then map converts the result into a JSON form, and then the subscribe allows us to access the returned data.

Next, CallApiWithPost() function is used to post data to the server. similar to the above explanation we get the data. but what the difference here is that, we have a body and a header here to pass along with the url.

body contains the data we want to send to the server. where as Content-Type in header.append tells the client what the content type of the returned content is.

Now change your home.html to look as follows.

Modify home.html file

home.html



<ion-header>

  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>

  </ion-header>

  <ion-content padding>
    <div style="text-align:center;" style="box-shadow: 0 4px 10px 0 rgba(0,0,0,0.2), 0 4px 20px 0 rgba(0,0,0,0.19);text-align: 
  center;">
     <button ion-button (click)="">Get</button>

     <button ion-button color="secondary" (click)="">Post/button>   
    </div>

    <ion-item *ngFor="let item of items">
      <img [src]="post.data.url" />
    </ion-item>

  </ion-content>

Now save the file and run the project, you will get an error saying " No http Provider ". To solve it simply import http module to app.module.ts file.

Modify app.module.ts file

app.module.ts



import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
 
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
 
@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}


That's it for this Post, if you have any queries regarding the post, please feel free to comment below.

Friday, 23 March 2018

How to Check App Availability in Ionic 2 and Ionic 3.

Have you ever came across a situation in your application development in ionic, where you need to use other app on the device. the situations be like, logging in using twitter, facebook etc. This Post we are going to see on, how to check if an app is installed on the user's device.


This post assumes that you already have the ionic project created and running. lets create a page in our project to implement the Check App Availability example.

Create a checkapp Page


Execute below command in your projects command prompt to add checkapp page to your project "pages" folder in "src" directory.

ionic generate page checkapp
The above code will generate checkapp folder in your project's src/pages folder.
Note : import the checkapp page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "checkapp.module.ts" file in your newly created page (ie. checkapp folder).

Modify app.module.ts file


app.module.ts


 import { BrowserModule } from '@angular/platform-browser';
        import { ErrorHandler, NgModule } from '@angular/core';
        import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

        import { MyApp } from './app.component';
        import { HomePage } from '../pages/home/home';
        import { ListPage } from '../pages/list/list';
        import { CheckappPage } from '../pages/checkapp/checkapp ';

        import { StatusBar } from '@ionic-native/status-bar';
        import { SplashScreen } from '@ionic-native/splash-screen';

        @NgModule({
        declarations: [
            MyApp,
            HomePage,
            ListPage,
            CheckappPage 
        ],
        imports: [
            BrowserModule,
            IonicModule.forRoot(MyApp)

        ],
        bootstrap: [IonicApp],
        entryComponents: [
            MyApp,
            HomePage,
            ListPage,
            CheckappPage 
        ],
        providers: [
            StatusBar,
            SplashScreen,
            {provide: ErrorHandler, useClass: IonicErrorHandler},

        ]
        })
        export class AppModule {}


Now That's over, lets get to the the plugin and functionality part. For this example we are going to use "App Availability" plugin from IONIC NATIVE.
Execute below command in your projects command prompt .

ionic cordova plugin add cordova-plugin-appavailability
for the plugin to work we should also install the app-availability node module also.
npm install --save @ionic-native/app-availability
Now, that we have installed the plugin, we should import the plugin to our component, and also inject it into our components constructor. Modify the components checkapp.ts file as shown below.

 import { AppAvailability } from '@ionic-native/app-availability';
 import { Platform } from 'ionic-angular';
 ...

 constructor(private appAvailability: AppAvailability, private platform: Platform) {
  ...
 }


since we have imported the plugin and also injected it to our components constructor. Now, it's time to check for the app availability on the device. lets write a function which executes when the user click on check availability button.

Modify checkapp.ts file

checkapp.ts


      import { Component } from '@angular/core';
      import { IonicPage, NavController, NavParams } from 'ionic-angular';
      import { AppAvailability } from '@ionic-native/app-availability';
      import { Platform } from 'ionic-angular';

      /**
       * Generated class for the PhotoviewerPage page.
       *
       * See https://ionicframework.com/docs/components/#navigation for more info on
       * Ionic pages and navigation.
       */

      @IonicPage()
      @Component({
        selector: 'page-photoviewer',
        templateUrl: 'photoviewer.html',
      })
      export class PhotoviewerPage {
        
        constructor(public navCtrl: NavController, public navParams: NavParams,private appAvailability: AppAvailability, private platform: Platform) {

        }

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

        checkAvailability(){
            let appName;
            if (this.platform.is('ios')) {
               appName = 'twitter://';
            } else if (this.platform.is('android')) {
               appName = 'com.twitter.android';
            }

            this.appAvailability.check(appName)
            .then(
               (yes: boolean) => { console.log(appName + ' is available') },
               (no: boolean) =>  { console.log(appName + ' is not available') }
            );
        }
      }


Above Given Code Explanation..

this.platform.is('') will return true if the platform is same as the given platform.
this.appAvailability.check() will take the app name as value, and checks if the given app is installed on the particular device. it will return boolean value as result.
That's it for this post. please leave a comment if you have any queries regarding the post.

Saturday, 17 March 2018

How to Implement Photo Viewer in Ionic 2 and Ionic 3

Photo Viewer plugin in IONIC NATIVE is intended to show a picture from an URL with zoom features. This plugin can display the given image in full screen with the ability to pan, zoom, and share the image.
In this Post we are going to look at how to view an image in ionic app with zoom, pan and share features.


This post assumes that you already have the ionic project created and running. lets create a page in our project to implement the photo viewer example.

Create a photoviewer page


Execute below command in your projects command prompt to add photoviewer page to your project "pages" folder in "src" directory.

ionic generate page photoviewer. 

the above code will generate photoviewer folder in your project's src/pages folder.
Note : import the photoviewer page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "photoviewer.module.ts" file in your newly created page (ie. photoviewer folder).
The "app.module.ts" should look something like this after photoviewer page is imported.

Modify app.module.ts file

app.module.ts



        import { BrowserModule } from '@angular/platform-browser';
        import { ErrorHandler, NgModule } from '@angular/core';
        import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

        import { MyApp } from './app.component';
        import { HomePage } from '../pages/home/home';
        import { ListPage } from '../pages/list/list';
        import { PhotoviewerPage } from '../pages/photoviewer/photoviewer';

        import { StatusBar } from '@ionic-native/status-bar';
        import { SplashScreen } from '@ionic-native/splash-screen';

        @NgModule({
        declarations: [
            MyApp,
            HomePage,
            ListPage,
            PhotoviewerPage 
        ],
        imports: [
            BrowserModule,
            IonicModule.forRoot(MyApp)

        ],
        bootstrap: [IonicApp],
        entryComponents: [
            MyApp,
            HomePage,
            ListPage,
            PhotoviewerPage 
        ],
        providers: [
            StatusBar,
            SplashScreen,
            {provide: ErrorHandler, useClass: IonicErrorHandler},

        ]
        })
        export class AppModule {}


That's it for the app.module.ts part. Now for the plugin and functionality part.
First install the Photo Viewer plugin from IONIC NATIVE. execute the below commands in your projects command prompt.
ionic cordova plugin add com-sarriaroman-photoviewer

npm install --save @ionic-native/photo-viewer

Now, Since the plugin is installed, import the plugin to your component, and also inject into your components constructor. Modify your components photoviewer.ts file as shown below.

  import { PhotoViewer } from '@ionic-native/photo-viewer';
  ...
  constructor(...,private photoViewer: PhotoViewer) { 
   ...
  }


Modify photoviewer.ts file.

photoviewer.ts



      import { Component } from '@angular/core';
      import { IonicPage, NavController, NavParams } from 'ionic-angular';
      import { PhotoViewer } from '@ionic-native/photo-viewer';

      /**
       * Generated class for the PhotoviewerPage page.
       *
       * See https://ionicframework.com/docs/components/#navigation for more info on
       * Ionic pages and navigation.
       */

      @IonicPage()
      @Component({
        selector: 'page-photoviewer',
        templateUrl: 'photoviewer.html',
      })
      export class PhotoviewerPage {
        imageSrc:string;
        constructor(public navCtrl: NavController, public navParams: NavParams,private photoViewer: PhotoViewer) {
          this.imageSrc = "https://4.bp.blogspot.com/-gV5KXvihmtY/WbAkZXv-S8I/AAAAAAAAAig/CaU_-gxdB68iBsMARMr8A0KqhjHFhZ5LQCLcBGAs/s320/logoionicsynclarge.png";
        }

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

        showImagewithTitle(img){
          this.photoViewer.show(img, 'My image title', {share: true});
        }

        showImage(img){
          this.photoViewer.show(img);
        }
      }




To make it simple i'm only adding one image to the imageSrc variable. here we have two functions showImagewithTitle & showImage. showImage function only displays the image with no further options but showImagewithTitle function has the option of displaying the image with title and share options.

Modify photoviewer.html file

photoviewer.html


  <ion-header>

  <ion-navbar>
    <ion-title>photoviewer</ion-title>
  </ion-navbar>

  </ion-header>

  <ion-content padding>
    <div style="text-align:center;" style="box-shadow: 0 4px 10px 0 rgba(0,0,0,0.2), 0 4px 20px 0 rgba(0,0,0,0.19);text-align: 
  center;">
        <img src="{{imageSrc}}}" (click)="showImage(imageSrc)" />
  </div>

  </ion-content>


That's it, this example will not work in web, so build the project and run it on device to check the PhotoViewer in action. fell free to comment below if you have any queries.

Friday, 16 March 2018

How to Implement Screen Orientation in Ionic 2 and Ionic 3

Some Mobile applications does not look attractive when in landscape mode and some in portrait mode. To overcome this, its best to lock the app to single orientation. Do you want to lock your app in portrait or landscape mode! then How to do it in ionic ?. This post explaing on how to implement Screen Orientation in ionic.


This post assumes that you already have the ionic project created and running.
we will first look at how to lock a particular page in the ionic application.

Create a screenorientation page.

Execute below command in your projects command prompt to add screenorientation page to your project "pages" folder in "src" directory.

ionic generate page screenorientation. 
the above code will generate screenorientation folder in your project's src/pages folder.
Note : import the screenorientation page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "screenorientation.module.ts" file in your new page file (ie in screenorientation folder). the "app.module.ts" should look something like this after socialsharing page is imported.

Modify app.module.ts file

app.module.ts


         import { BrowserModule } from '@angular/platform-browser';
        import { ErrorHandler, NgModule } from '@angular/core';
        import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

        import { MyApp } from './app.component';
        import { HomePage } from '../pages/home/home';
        import { ListPage } from '../pages/list/list';
        import { ScreenorientationPage } from '../pages/screenorientation/screenorientation';

        import { StatusBar } from '@ionic-native/status-bar';
        import { SplashScreen } from '@ionic-native/splash-screen';

        @NgModule({
        declarations: [
            MyApp,
            HomePage,
            ListPage,
            ScreenorientationPage
        ],
        imports: [
            BrowserModule,
            IonicModule.forRoot(MyApp)

        ],
        bootstrap: [IonicApp],
        entryComponents: [
            MyApp,
            HomePage,
            ListPage,
            ScreenorientationPage
        ],
        providers: [
            StatusBar,
            SplashScreen,
            {provide: ErrorHandler, useClass: IonicErrorHandler},

        ]
        })
        export class AppModule {}


That's it for the app.module.ts part. Now lets see how to lock the orientation of our app.
We will be using Screen Orientation plugin that's available as part of Ionic Native.
To install the plugin execute the below commands in your command prompt:
ionic cordova plugin add cordova-plugin-screen-orientation

npm install --save @ionic-native/screen-orientation
Now, import the installed plugin into your component, and also inject into your components constructor. Modify your components screenorientation.ts file as shown below.

     import { ScreenOrientation } from '@ionic-native/screen-orientation';

     constructor(...,private screenOrientation: ScreenOrientation) { ... }


Next, for the functionality part.
Copy and Paste the below given code to your components ionViewDidLoad function in ts file ie in this example screenorientation.ts.


      // check for current orientation

      console.log(this.screenOrientation.type);

      // set orientation to landscape

      this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.LANDSCAPE);

      // allow user rotate of app

      this.screenOrientation.unlock();

      // checks for orientation changes

      this.screenOrientation.onChange().subscribe(
        () => {
            console.log("Orientation Changed");
        }
      );


Above Code Explanation

As the comments says, the screenOrientation.type checks if the orientation is in portrait or landscape. this is particularly help full when you want to check for orientation.
next, screenOrientation.lock method lock's screen orientation either in landscape or portrait mode. it takes either screenOrientation.ORIENTATIONS.LANDSCAPE or screenOrientation.ORIENTATIONS.PORTRAIT as input.
The screenOrientation.unlock method unlockes the screen orientation. it does not need any input.

The screenOrientation.onChange method checks for orientation changes on device.

Lock orientation for the whole app

To lock the orientation for the whole app, we should modify app.component.ts as shown below.

app.component.ts



  import { ScreenOrientation } from '@ionic-native/screen-orientation';
  ...
  constructor(...,private screenOrientation: ScreenOrientation) {
  ...
  }

  initializeApp() {

    this.platform.ready().then(() => {

      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.

      this.statusBar.styleDefault();
      this.splashScreen.hide();

      // locks the orientation in portratit mode
      this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
    });

   }


this will lock the screen orientation to portrait mode, when the platform.ready() method executes.
that's it for this post, please leave a comment if you have any queries regarding the post.

Wednesday, 14 March 2018

Implementing Social Sharing in Ionic 2 and ionic 3.

Social Sharing in ionic is used to Share Text, Files, Images, and Links via Social Networks, SMS, and Email. In ionic, Social Sharing can be achieved by Ionic Native. Ionic Native allows to add native functionality to ionic application via plugins.
In this Post we are going to look at, how to integrate social sharing functionality in an ionic application.
This post assumes that you already have the ionic project created and running.

Create a socialsharing page.

Execute below command in your projects command prompt to add socialsharing page to your project "pages" folder in "src" directory.

ionic generate page socialsharing

this will generate socialsharing folder in your project's src/pages folder.
Note : import the socialsharing page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "socialsharing.module.ts" file in your new page file (ie in socialsharing folder). the "app.module.ts" should look something like this after socialsharing page is imported.

Modify app.module.ts file

app.module.ts



        import { BrowserModule } from '@angular/platform-browser';
        import { ErrorHandler, NgModule } from '@angular/core';
        import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

        import { MyApp } from './app.component';
        import { HomePage } from '../pages/home/home';
        import { ListPage } from '../pages/list/list';
        import { SocialsharingPage } from '../pages/socialsharing/socialsharing';

        import { StatusBar } from '@ionic-native/status-bar';
        import { SplashScreen } from '@ionic-native/splash-screen';

        @NgModule({
        declarations: [
            MyApp,
            HomePage,
            ListPage,
            SocialsharingPage
        ],
        imports: [
            BrowserModule,
            IonicModule.forRoot(MyApp)

        ],
        bootstrap: [IonicApp],
        entryComponents: [
            MyApp,
            HomePage,
            ListPage,
            SocialsharingPage
        ],
        providers: [
            StatusBar,
            SplashScreen,
            {provide: ErrorHandler, useClass: IonicErrorHandler},

        ]
        })
        export class AppModule {}



That is all for the app.module file your app should run fine now.

Install the Social Sharing plugin.


Execute below commands in your projects command prompt to install ionic Social Sharing plugin to your project.

ionic cordova plugin add cordova-plugin-x-socialsharing

npm install --save @ionic-native/social-sharing
Now, import it in your component, and also inject into your components constructor.
Copy and paste the below give code to the socialsharing.ts file imports.

   
   import { SocialSharing } from '@ionic-native/social-sharing';
   
   constructor( ..., private socialSharing: SocialSharing) { ... }
   

Next, for the share functionality. if you want to open a sheet with all the social media options, use the below share function .

  this.socialSharing.share('Message', 'Subject', 'http://www.ionicsync.com/images/logo.png', 'http://www.ionicsync.com').then(() => {

     console.log('Shared Successfully');

  }).catch(() => {

     console.log('Sharing Failed');

  });

Sharing via some applications is not support due to some reasons , for that we should first check if it is supported. Below function checks if sharing via email is supported.


  this.socialSharing.canShareViaEmail().then(() => {
    console.log('Sharing via email is possible');
    this.socialSharing.shareViaEmail('Body', 'Subject', ['recipient@example.org']).then(() => {
       console.log('Success!');
     }).catch(() => {
       console.log('Error!');
     });
  }).catch(() => {
    console.log('Sharing via email is not possible');
  });


This can be done with all the social applications the plugin supports. We also have shareWithOptions().


  shareViaOptions(){
       var options = {
        message: 'share via',
        subject: 'Please select any social media to share.',
        url: 'http://www.ionicsync.com',
        chooserTitle: 'SHARE' // Android only, you can override the default share sheet title
      }


      this.socialSharing.shareWithOptions(options).then((res) => {
       console.log('Success!');
      }).catch(() => {
       console.log('Error!');
      });
      
  }

Your socialsharing.ts file should look something like this.

socialsharing.ts


  
  
   import { SocialSharing } from '@ionic-native/social-sharing';
   ...

   constructor( ..., private socialSharing: SocialSharing) { ... }

   @IonicPage()
   @Component({
    selector: 'page-socialsharing',
    templateUrl: 'socialsharing.html',
   })
   export class SocialSharing {
     ionViewDidLoad() {
           console.log('ionViewDidLoad SharePage');
     }  

     share(){
            this.socialSharing.share('Message', 'Subject', 'http://www.ionicsync.com/images/logo.png', 'http://www.ionicsync.com').then(() => {

                console.log('Shared Successfully');

            }).catch(() => {

                console.log('Sharing Failed');

            });
    };

    checkShare(){
        this.socialSharing.canShareViaEmail().then(() => {
                console.log('Sharing via email is possible');
                this.socialSharing.shareViaEmail('Body', 'Subject', ['recipient@example.org']).then(() => {
                console.log('Success!');
                }).catch(() => {
                console.log('Error!');
                });
            }).catch(() => {
                console.log('Sharing via email is not possible');
            });
    } ;  

   shareViaOptions(){
      var options = {
        message: 'share via',
        subject: 'Please select any social media to share.',
        url: 'http://www.ionicsync.com',
        chooserTitle: 'SHARE' // Android only, you can override the default share sheet title
      }


      this.socialSharing.shareWithOptions(options).then((res) => {
       console.log('Success!');
      }).catch(() => {
       console.log('Error!');
      });
      
    };
   
   }


One more thing is, you should also import the "SocialSharing" to your apps app.module.ts file, otherwise you will get a provider issue. That's it if you have any queries, please leave a comment below.

Thursday, 1 March 2018

How to Implement Barcode Scanner in ionic 2 and ionic 3.

Barcode Scanner is used to scan QR/Bar Codes which contains url links, geo coordinates, and text. In this Post we are going to use Cordova plugin : phonegap-plugin-barcodescanner ,this Plugin opens a camera view and automatically starts scanning for a barcode, it returns the data back as a response when it detects a QR/Bar code.
First lets create a page in our ionic project using the below command.
ionic generate page qrcode
Here i'm creating a page with name qrcode, once the command is executed a folder will be created with name qrcode in src/pages folder of the current ionic project. Now since our page is created, lets install the barcode scanner plugin. run the following command to install cordova barcode scanner plugin.
ionic cordova plugin add phonegap-plugin-barcodescanner
we also need the native plugin for the barcode to work properly, so run the below command also.
npm install --save @ionic-native/barcode-scanner
Note : for the above command to work you should have Node.js installed Since the above plugins are installed, for the plugin to work,we should tell the app to import the plugin. modify app.module.ts to include below code.

app.module.ts

import { BarcodeScanner } from '@ionic-native/barcode-scanner';
and in NgModule's providers add BarcodeScanner as shown below.

app.module.ts


  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    BarcodeScanner
  ]
  
lets head to qrcode folder we have created, Open qrcode.html and replace the content with the below code provided. Copy and Pase the Below code to your components html template.

qrcode.html


<ion-content padding>

  <p *ngIf="showScanQRCode" class="scanText">Click the Button to Scan.</p>
    <div *ngIf="scannedData !=undefined" class="scanCode">
     <p>Welcome to QRCODE Scanner</p>
     </br>    
     <p>{{scannedData}}</p>  
    </div>

  <ion-footer>
    <button style="margin-bottom: 35px !important;" ion-button full (click)="openScanner()" >Scan Code</button>            
  </ion-footer>

</ion-content>

That's it for the html part, now lets head to qrcode.ts file, modify your file to inclue the following code provided. Copy and Pase the Below code to your components ts file.

qrcode.ts


import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BarcodeScanner } from '@ionic-native/barcode-scanner';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  scannedData:any;
  showScanQRCode:Boolean = true;
  constructor(public navCtrl: NavController,private barcodeScanner: BarcodeScanner) {
  }


  openScanner(){
    console.log("Opening Scanner");
    this.barcodeScanner.scan().then((barcodeData) => {
      this.showScanQRCode = false;
      // Success! Barcode data is here
       console.log("BarCode data",barcodeData);
       this.scannedData = barcodeData.text;
      
     }, (err) => {
         // An error occurred
         console.log("BarCode error",err);
         
     });
  }

}

Here we are importing BarcodeScanner from ionic-native, and the injected BarcodeScanner to HomePage class's constructor. The openScanner function is called when we click on Scan Code Button. barcodeScanner.scan() method open's qrcode scanner in a new view and starts scanning for qrcode or barcode and when provided one its scans it and retrns response as text. In this example it barcodeData.text returns www.ionicsync.com, since the qrcode contains it.
Now for the css part, copy and paste the below code to your components .scss file.

  .scanText{
    text-align: center;
    position: sticky;
    top: 40%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
  }

  .scanCode{
    display: block;
    text-align: center;
    margin-top: 50%;
  }

That's it, feel free to comments below if you have any doubt's or queries.

Saturday, 24 February 2018

How to Implement Pull To Refresh functionality in Ionic 2 and ionic 3

Ionic Framework Comes with a ion-refresher Component that makes it easy for developers to implement pull to refresh content functionality in your ionic application. Pull to Refresh can be used to refresh the already existing items or to add more items to the already existing items like timeline. In this example we will see how to implement pull to refresh functionality which adds an country name to the list every time the list is pulled. This tutorial assumes that you already have the project setup and running.

Create a countrylist page.

Execute below command in your projects command prompt to add countrylist page to your project "pages" folder in "src" directory.


  ionic generate page countrylist
this will generate contrylist folder in your project's src/pages folder. Note : import the countrylist page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "countrylist.module.ts" file in your new page file (ie in countrylist folder). the "app.module.ts" should look something like this after countrylist page is imported.

Modify app.module.ts file

app.module.ts



import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { CountrylistPage } from '../pages/countrylist/countrylist';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    CountrylistPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    CountrylistPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},

  ]
})
export class AppModule {}


That is all for the app.module file your app should run fine now.

Modify countrylist.html template

Copy and paste the below give code just below the opening content tag ie, ion-content.

countrylist.html


  <ion-refresher (ionRefresh)="doRefresh($event)">
        <ion-refresher-content
        pullingIcon="md-arrow-dropdown"
        pullingText="Pull to refresh"
        refreshingSpinner="crescent"
        refreshingText="Refreshing...">
      </ion-refresher-content>
      </ion-refresher>

above code provide you with all the Customizing options to modify the ui of Refresher Content or you can use the default ui by simply using the below given code.

   <ion-refresher (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>

Now that the UI part is complete, lets head to the countrylist.ts file to implement the ion-refresher functionality.

Modify countrylist.ts file as shown below.

Copy and Paste the below given code in to your countrylist.ts file.

countrylist.ts


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

    /**
    * Generated class for the CountrylistPage page.
    *
    * See https://ionicframework.com/docs/components/#navigation for more info on
    * Ionic pages and navigation.
    */

    @IonicPage()
    @Component({
    selector: 'page-countrylist',
    templateUrl: 'countrylist.html',
    })
    export class CountrylistPage {
    countryList:any;
    moreCountries:any;
    countryCount = 0;
    constructor(public navCtrl: NavController, public navParams: NavParams) {
        this.countryList = [];
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad CountrylistPage');
        this.moreCountries=["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Cape Verde","Cayman Islands","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cruise Ship","Cuba","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kuwait","Kyrgyz Republic","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Mauritania","Mauritius","Mexico","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Namibia","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","Norway","Oman","Pakistan","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Satellite","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","South Africa","South Korea","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","St. Lucia","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Uganda","Ukraine","United Arab Emirates","United Kingdom","Uruguay","Uzbekistan","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"]
    }

    doRefresh(refresher) {
        console.log('Begin async operation', refresher);

        this.countryList.push(this.moreCountries[this.countryCount])
        this.countryCount = this.countryCount + 1;

        setTimeout(() => {
        console.log('Async operation has ended');
        refresher.complete();
        }, 100);
    }

    }

What the above code does is, when ever you pull the page down it triggers the ionRefresh event, which intern calls the doRefresh function. the doRefresh function then checks the countryCount and pushes the country from moreCountries array to countryList array, which gets updated in the ionic content view. refresh.complete() completes/stops the refresh process. we have set a timeout here to make sure that the spinner spins until the content is updated. it may help someone, so i'm posting the full html code below. feel free to comment below

full countrylist.html template code


<ion-header>

  
  <ion-navbar>
    
          <button ion-button menuToggle>
              <ion-icon name="menu"></ion-icon>
            </button>
          <ion-title>Countries</ion-title>
    
        </ion-navbar>

</ion-header>


<ion-content padding>

  <ion-refresher (ionRefresh)="doRefresh($event)">
    <ion-refresher-content
    pullingIcon="md-arrow-dropdown"
    pullingText="Pull to refresh"
    refreshingSpinner="crescent"
    refreshingText="Refreshing...">
  </ion-refresher-content>
  </ion-refresher>

  <ion-list no-lines>
    <ion-item *ngFor="let item of countryList" style="font-weight: 600;font-family: roboto;">
      {{item}}
    </ion-item>
  </ion-list>


<div *ngIf="countryList.length == 0" style="height: 100%;position: relative;top: 45%;text-align: center;">
    <div style="font-size: 20px;text-align: center;color: #90949c;">Pull to fetch Countries</div>
</div>
</ion-content>

Friday, 16 February 2018

Creating an Intro Slider in Ionic 2 and ionic 3 Application

Every Mobile Application needs an intro slides to notify user about the features of the app they have installed. Intro slides gives the users the much needed information about the app, a tutorials on the welcome screen. Ionic Framework Provides developers with a component called ion-slides which makes it easy to create an intro slider for your ionic application.

Create an Intro Page

Execute below command in your projects command prompt to add intro page to your project "pages" folder in "src" directory.


  ionic generate page intro
this will generate intro folder in your project's src/pages folder.
Note : import the intro page in to your app module and add it to the declarations and entryComponents, if your cli does not create an "intro.module.ts" file in your new page file (ie in intro folder). the "app.module.ts" should look something like this after intro page is imported.

Modify app.module.ts file

app.module.ts


import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { IntroPage } from '../pages/intro/intro';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    IntroPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)

  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    IntroPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},

  ]
})
export class AppModule {}

Now, that's out of or way, let's head forward and modify our intro template page.

Change intro.html file as given below

Copy and Paste the below html code in your intro.html file.

intro.html


    <ion-content padding>
  <ion-slides (ionSlideDidChange)="slideChanged()"> 
    <ion-slide *ngFor="let item of IntroInfo">
      <img class="imageStyle" src="{{item.image}}"/>    
      <h1>{{item.subject}}</h1>
      <p *ngIf="item.description">{{item.description}}</p>
      <button *ngIf="item.buttontext" ion-button color="light">{{item.buttontext}}</button>
    </ion-slide>

  </ion-slides>
</ion-content>  

ionSlideDidChange event call the slideChanged method when ever the slide is changed. ngIf condition for button is, that it will be only viewable when ther's a buttontext key in the list item. now lets check the ts file for the corresponding intro.html file.

Modify intro.ts file as shown below.

Copy and Paste the below ts code in your intro.ts file.

intro.ts


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

/**
 * Generated class for the IntroPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-intro',
  templateUrl: 'intro.html',
})
export class IntroPage {
  @ViewChild(Slides) slides: Slides;
  public IntroInfo:any;

  constructor(public navCtrl: NavController, public navParams: NavParams) {
     this.IntroInfo = [{image:"assets/welcome.png",subject:"MyWeather",description:"Get all the weather information in one place."},
                       {image:"assets/sunny.png",subject:"Its hot Today!",description:"Whether it's hot.."},
                       {image:"assets/freezing.png",subject:"climate is freezing, isn'nt it!",description:"whether it's freezing.."},
                       {image:"assets/continue.png",subject:"Get Started..",buttontext:"Continue"}]
  }

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

    // Below function when executed starts autoplay of the slides.

  autoSlideStart(){
    this.slides.startAutoplay()
  }

   // Below function when executed stops autoplay of the slides.

  autoSlideStop(){
    this.slides.stopAutoplay()
  }
    // Below function when executed Traverse to a specified slide given.

  goToSlide() {
    this.slides.slideTo(2, 500, true);  // where 2 is the index, 500 is speed and true is Whether or not to run ionSlideWillChange/ionSlideDidChange events when the slide is changed.
  }

    // Below function when executed will Traverse to Next slide.

  goToNSlide(){
    this.slides.slideNext(500, false)     // where 500 is speed and false is Whether or not to run ionSlideWillChange/ionSlideDidChange events when the slide is changed.
  }

    // Below function when executed will Traverse to previous slide.

  goToPSlide(){
    this.slides.slidePrev(500, false)     // where 500 is speed and false is Whether or not to run ionSlideWillChange/ionSlideDidChange events when the slide is changed.
  }

    // Below function Get's the index of the active slide.

  slideChanged() {
    let currentIndex = this.slides.getActiveIndex();
    console.log('Current index is', currentIndex);
  }

    // Below function Get's the index of the previous slide.

  getBeforeIndex(){
    let previousIndex = this.slides.getPreviousIndex();
    console.log('Previous index is', previousIndex);
  }

    // Below function Get whether or not the current slide is the first slide.

  isSlideFirst(){
    let firstSlide = this.slides.isBeginning()
    console.log('Current slide is the first slide', firstSlide);
  }

    // Below function Get's whether or not the current slide is the last slide.

  isSlideEnd(){ 
    let endSlide = this.slides.isEnd()
    console.log('Current slide is the last slide', endSlide);
  }

  // Below function gets the total number of slides.

  slideLength(){   
    let endSlide = this.slides.length();
    console.log('Number of slides are : ', endSlide);
  }

  // Below function when set to true the user will not be able to swipe to the next slide. Set to false to unlock this behaviour.

  lockNextSlide(){
    let shouldLockSwipeToNext = true; //  shouldLockSwipeToNext can be either true/false
    let lockNSlide = this.slides.lockSwipeToNext(shouldLockSwipeToNext);
    console.log('Number of slides are : ', lockNSlide); 
  }

  // Below function when set to true the user will not be able to swipe to the previous slide. Set to false to unlock this behaviour.

  lockPrevSlide(){
    let shouldLockSwipeToPrev = false; //  shouldLockSwipeToPrev can be either true/false
    let lockNSlide = this.slides.lockSwipeToPrev(shouldLockSwipeToPrev);
    console.log('Number of slides are : ', lockNSlide); 
  }

  // Below function when set to true user's can not swipe in either direction on slide. False allows swiping in both directions.

  lockAllSlide(){
    let shouldLockSwipes = true; //  shouldLockSwipes can be either true/false
    let lockNSlide = this.slides.lockSwipes(shouldLockSwipes);
    console.log('Number of slides are : ', lockNSlide); 
  }

  // Below function when executed update's the slides structure. Call this if you’ve added or removed child slides.

  updateTheSlides(){
    this.slides.update()
  }
  

}

the above ts file contains all the methods, ionic slides provide to us. their use and functionality is written as comments above the respective functions. thats it, if you like you can adjust the slide image width with the below class.

styling the slides

Copy and Paste the below css code to your Components .scss file.

intro.scss


 page-intro {
   .imageStyle{
       width:50%;
   }
}

that's it, now save the changes and restart the server to view the intro slides in action.

Tuesday, 6 February 2018

How to implement Gestures in ionic 2 and ionic 3

Gestures on a phone can be very useful, when implementing functionality for images like pinch to zoom, long press to get more options regarding image editing. They can be used further more for different purposes like swipe to delete an item etc. In this post we are going to see how to implement Gestures in ionic framework. We will see how to use gestures like press, pan, tap and swipe. This tutorial assumes you already have the ionic project up and running. Now generate a new page named "gesture" with the following command.

  ionic generate page gesture

Copy and Paste the html code to your Components .html file.

  <ion-header>

  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Gesture</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
 
  <ion-card (tap)="tapEvent($event)" class="cardStyle">
    <ion-item>
      Tapped: {{tap}} times
    </ion-item>
  </ion-card>

  <ion-card (press)="pressEvent($event)"  class="cardStyle">
    <ion-item>
      Pressed: {{press}} times
    </ion-item>
  </ion-card>

  <ion-card (pan)="panEvent($event)"  >
    <ion-item [ngStyle]="calculateStyle()">
      Panned: {{pan}} times <br>
      Panning: {{panDirection}}
    </ion-item>
  </ion-card>

  <ion-card (swipe)="swipeEvent($event)" (tap)="changeColor()" class="cardStyle">
    <ion-item id="swipeItem" >
      Swiped: {{swipe}} times
    </ion-item>
  </ion-card>

</ion-content>

In the above code we have defined cards individually for every event with their corresponding function calls.
Copy and Paste the below ts code to your Components .ts file.

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

/**
 * Generated class for the GesturePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-gesture',
  templateUrl: 'gesture.html',
})
export class GesturePage {

  public press: number = 0;
  public pan: number = 0;
  public swipe: number = 0;
  public tap: number = 0;
  public pinch: number = 0;
  public panDirection:string = "";
  public bgHorz:   number = 0 ;
  public lastBgH:  number = 0 ;
  public bgVert:   number = 0 ;
  public lastBgV:  number = 0 ;

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

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


// function to call when item is pressed.

  pressEvent(e) { 
    this.press++;
  }

// function to call when item is panned.

  panEvent(e) {
    console.log(e.additionalEvent+"||"+e.direction)
    console.log(e.deltaX +"||"+e.deltaY)
    this.pan++
    if(e.direction == 1){
      this.panDirection = "None";
    }else if(e.direction == 2){
      this.panDirection ="Left";    
    }else if(e.direction == 4){
      this.panDirection = "Right";    
    }else if(e.direction == 6){
      this.panDirection = "HORIZONTAL";    
    }else if(e.direction == 8){
      this.panDirection = "Up";     
    }else if(e.direction == 16){
      this.panDirection = "Down";     
    }else if(e.direction == 24){
      this.panDirection = "VERTICAL";     
    }else{
      this.panDirection = "ALL";
    }

   // logic to pan image

    var stepH = e.deltaX /10 ;
    var stepV = e.deltaY /10 ;

    this.bgHorz = this.bgHorz + (this.lastBgH - stepH) ;
    if (this.bgHorz < 0) {
       this.bgHorz = 0 ;
    } else {
       if (this.bgHorz > 100)
          this.bgHorz = 100 ;
    }

    this.bgVert = this.bgVert + (this.lastBgV - stepV) ;
    if (this.bgVert < 0) {
       this.bgVert = 0 ;
    } else {
       if (this.bgVert > 100)
          this.bgVert = 100 ;
    }

    this.calculateStyle()

  }

// function to call when item panning is ended.

  panEnd($event){
    //events  pan, panstart, panmove, panend, pancancel, panleft, panright, panup, pandown
    console.log("Panning Ended")
  }


// function to calculate the position of image when it is panned.

  calculateStyle() {
    var style = {
        backgroundImage : 'url("../assets/ionicFramework.png")',
        backgroundPositionX : this.bgHorz+'%',
        backgroundPositionY : this.bgVert+'%',
        backgroundRepeat: 'no-repeat',
        height:"200px"
    } ;
    return style ;
 }


// function to call when item is swiped.

  swipeEvent(e) {
    this.swipe++
    console.log('' + e.direction);
    // Swipe Direction "DIRECTION_LEFT"
    if(e.direction == 2){
      document.getElementById("swipeItem").style.backgroundColor = "#ff0026db"
      document.getElementById("swipeItem").style.color = "white"
    }
    // Swipe Direction "DIRECTION_RIGHT"
    if(e.direction == 4){
      document.getElementById("swipeItem").style.backgroundColor = "#189666"
      document.getElementById("swipeItem").style.color = "white"
      
    }

  /** --Direction for swip event--

      DIRECTION_NONE         1
      DIRECTION_LEFT         2
      DIRECTION_RIGHT        4
      DIRECTION_UP           8
      DIRECTION_DOWN         16
      DIRECTION_HORIZONTAL   6
      DIRECTION_VERTICAL     24
      DIRECTION_ALL          30

     --Direction for swip event-- **/
  }

// function to call when item is tapped.

  tapEvent(e) {
    this.tap++
  }


// function to call when qwiped item is tapped.

  changeColor(){
    document.getElementById("swipeItem").style.backgroundColor = "white"
    document.getElementById("swipeItem").style.color = "black"
    
  }

}

Now run the project to check the events in action. feel free to comment below for any queries.

Saturday, 18 November 2017

HighCharts Column Drilldown Chart Implementation in ionic 2 and 3

HighCharts DrillDown Chart Implementation in ionic 2 and 3 Highcharts are interactive charts for web pages, which makes it easy for developers to integrate live charts in to their project.
In this tutorial we will be working on how to implement HighCharts column drilldown chart in ionic 2 and 3 project.
First of all modify your Project code as shown below,
Note: if you want to check out the code or you only want the code, you can download the component HERE, after downloading just copy and paste the component in to your projects src/pages folder that's it.
Copy & Paste the below code to your Components html page

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>HIghChart</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

</ion-content>

this div container with id "container" is the place where the highchart is rendered.
Copy & Paste the ts code to your Components .ts file.


import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

declare var Highcharts;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {
    
  }
  
  
  ionViewDidLoad() {
    console.log('ionViewDidLoad DateTimePickerPage');
 this.drilldown();
  }
  
  drilldown(){
     // Create the chart
  Highcharts.chart('container', {
   chart: {
    type: 'column'
   },
   title: {
    text: 'Browser market shares. January, 2015 to May, 2015'
   },
   subtitle: {
    text: 'Click the columns to view versions. Source: netmarketshare.com.'
   },
   xAxis: {
    type: 'category'
   },
   yAxis: {
    title: {
     text: 'Total percent market share'
    }

   },
   legend: {
    enabled: false
   },
   plotOptions: {
    series: {
     borderWidth: 0,
     dataLabels: {
      enabled: true,
      format: '{point.y:.1f}%'
     }
    }
   },

   tooltip: {
    headerFormat: '{series.name}
', pointFormat: '{point.name}: {point.y:.2f}% of total
' }, series: [{ name: 'Brands', colorByPoint: true, data: [{ name: 'Microsoft Internet Explorer', y: 56.33, drilldown: 'Microsoft Internet Explorer' }, { name: 'Chrome', y: 24.03, drilldown: 'Chrome' }, { name: 'Firefox', y: 10.38, drilldown: 'Firefox' }, { name: 'Safari', y: 4.77, drilldown: 'Safari' }, { name: 'Opera', y: 0.91, drilldown: 'Opera' }, { name: 'Proprietary or Undetectable', y: 0.2, drilldown: null }] }], drilldown: { series: [{ name: 'Microsoft Internet Explorer', id: 'Microsoft Internet Explorer', data: [ [ 'v11.0', 24.13 ], [ 'v8.0', 17.2 ], [ 'v9.0', 8.11 ], [ 'v10.0', 5.33 ], [ 'v6.0', 1.06 ], [ 'v7.0', 0.5 ] ] }, { name: 'Chrome', id: 'Chrome', data: [ [ 'v40.0', 5 ], [ 'v41.0', 4.32 ], [ 'v42.0', 3.68 ], [ 'v39.0', 2.96 ], [ 'v36.0', 2.53 ], [ 'v43.0', 1.45 ], [ 'v31.0', 1.24 ], [ 'v35.0', 0.85 ], [ 'v38.0', 0.6 ], [ 'v32.0', 0.55 ], [ 'v37.0', 0.38 ], [ 'v33.0', 0.19 ], [ 'v34.0', 0.14 ], [ 'v30.0', 0.14 ] ] }, { name: 'Firefox', id: 'Firefox', data: [ [ 'v35', 2.76 ], [ 'v36', 2.32 ], [ 'v37', 2.31 ], [ 'v34', 1.27 ], [ 'v38', 1.02 ], [ 'v31', 0.33 ], [ 'v33', 0.22 ], [ 'v32', 0.15 ] ] }, { name: 'Safari', id: 'Safari', data: [ [ 'v8.0', 2.56 ], [ 'v7.1', 0.77 ], [ 'v5.1', 0.42 ], [ 'v5.0', 0.3 ], [ 'v6.1', 0.29 ], [ 'v7.0', 0.26 ], [ 'v6.2', 0.17 ] ] }, { name: 'Opera', id: 'Opera', data: [ [ 'v12.x', 0.34 ], [ 'v28', 0.24 ], [ 'v27', 0.17 ], [ 'v29', 0.16 ] ] }] } }); } }
try running the code now, you will get an error saying "Highcharts" is not declared, that's because we had'nt imported the highcharts js into our app.
Copy & Paste the below CDN links to your index.html.


<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/data.js"></script>
<script src="https://code.highcharts.com/modules/drilldown.js"></script>

That's it, now save it and run the code. you should see you highcard working.

Friday, 17 November 2017

How to Implement Form Validations in Ionic 2 and 3

We generally implement input fields with [(ngModel)] which uses two way data binding between template and variable, so that what you type or enter in the input field gets binded to variable that is accessible in the .ts file. for example if you have an input field like below:


<ion-input type="text" [(ngModel)]="myInput"></ion-input>


the value you entered in the above input gets binded to this.myInput which can be accesses from respective class definition.
Although the above procedure is fair to use, but if you want to implement validations, it can be somewhat time consuming.
So, to overcome this in this tutorial we are going to learn, how to implement complex form validations ionic 2/3 applications.
Note: if you want to check out the code or you only want the code, you can download the component here, after downloading just copy and paste the component in to your projects src/pages folder that's it.
Now lets get to implemeting form validatons in ionic framework,

We will be using FormGroup & FormControl in this tutorial to create and validate form's in ionic 2/3.
This tutorial assumes that you already have the project created in ionic 2/3.

Copy & Paste the below code to your Components html page


<ion-header>
  
    <ion-navbar>

	    <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
      <ion-title>Form Validation</ion-title>

    </ion-navbar>
  
</ion-header>

<ion-content>
  
<ion-list no-lines>
      <p style="padding: 15px;"><b>Title:</b> A tutorial to demonstrate Form Validations in ionic 2/3.</p>
	  
      <form [formGroup]="signUp" (ngSubmit)="SignUpForm()">

        <ion-item class="itemStyle">
          <ion-label>Name</ion-label>
          <ion-input type="text" formControlName="name" clearInput [class.invalid]="!signUp.controls.name.valid && signUp.controls.name.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Email</ion-label>
          <ion-input type="email" formControlName="email" clearInput [class.invalid]="!signUp.controls.email.valid && signUp.controls.email.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Contact Number</ion-label>
          <ion-input type="number" formControlName="contactnumber" clearInput [class.invalid]="!signUp.controls.contactnumber.valid && signUp.controls.contactnumber.dirty"></ion-input>
        </ion-item>

        <ion-item class="itemStyle">
          <ion-label>Password</ion-label>
          <ion-input type="password" formControlName="password" clearInput [class.invalid]="!signUp.controls.password.valid && signUp.controls.password.dirty"></ion-input>
        </ion-item>

        <button ion-button block type="submit" [disabled]="!signUp.valid" style="background-color: #343434;width: 90%;margin: auto;color:white;font-weight: 600;margin-top:20px;">Sign Up</button>
      
      </form>
</ion-list>

</ion-content>



Here, we have a formGroup property with a value of signUp which we are going to create the form with. if not, You might have already observed that we dont have [(ngModel)] here because its work is carried out by formControlName here. every input here has an formControlName which are used to carry and validate input values.
[class.invalid] is applied if the particular formControlName is invalid or dirty. [disabled]="!signUp.valid" disables submit button until the form is valid.
Copy & Paste the ts code to your Components .ts file.


import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams} from 'ionic-angular';
import {Validators, FormBuilder, FormGroup } from '@angular/forms';

/**
 * Generated class for the FormcontrolPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-formcontrol',
  templateUrl: 'formcontrol.html',
})
export class FormcontrolPage {

  private signUp : FormGroup;

  constructor(public navCtrl: NavController, public navParams: NavParams, private formBuilder: FormBuilder) {
    
    let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
    
    this.signUp = this.formBuilder.group({

            name: ['', Validators.compose([Validators.maxLength(30), Validators.pattern('[a-zA-Z ]*'), Validators.required])],
            password: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
            email: ['', Validators.compose([Validators.required, Validators.pattern(EMAIL_REGEXP)])],
            contactnumber: ['', Validators.compose([Validators.maxLength(10), Validators.required])],
    
    });
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad FormcontrolPage');
  }
  
  SignUpForm(){
	  console.log(this.signUp.value)
  }

}


dont forget to include this in you .scss file.

Copy and Paste the Below css code to you components .scss file.


    .itemStyle{
        margin-bottom: 15px !important;
        width: 90%;
        margin: auto;
        border-radius: 8px;
        background-color: #eaeaea;
    }  

    .invalid {
		border: 1px solid #f90000;
		border-radius: 5px;
    }


Now that you have all the code in place, lets get to the explanation part, shall we.
Here we are importing Validators, FormBuilder, FormGroup into our page/component from @angular/forms. FormBuilder will be used to create FormGroup which have all the FormControls, which intern have all the values that you entered into the form.
Create a member variable signUp of type FormGroup. Now can use this signUp member variable to create our form.The formBuilder.group function is used to create our FormGroup by supplying an object containing each of our FormControls(ie. formControlName).
Validators.compose function is used to set multiple validators. default validators that are commonly used for validation are,
.Validators.required
.Validators.minLength
.Validators.maxLength
.Validators.pattern


The required validator requires that the value is not empty, minLength and maxLength ensure that the length of the input is of a certain length, and where as pattern uses a regex pattern to validate the form input.

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>