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.