Ionic 5|4 Add Barcode/ QR Code Scanner/ Encoder Generator using Native Plugin

In this tutorial, we will implement a Barcode or QR Scanner / Encoder plugin in an Ionic application. Barcodes and QR codes are widely used for multiple purposes like to add a link where a user doesn’t need to type the whole URL it can be easily scanned from a QR code. Barcodes can also be seen everywhere on the day to day items like eatables clothes etc, we can wimple scan these barcodes to get information like item code date of manufacturing, prices, etc.

We will create a similar app to scan these codes.

Using React? Check this tutorial to implement Barcode Scanner in Ionic React

 

Let’s start…

 

Version Check

@ionic/cli 

   _             _
  (_) ___  _ __ (_) ___
  | |/ _ \| '_ \| |/ __|
  | | (_) | | | | | (__
  |_|\___/|_| |_|_|\___| CLI 6.4.1

# Update Ionic CLI

Run following npm command to update the Ionic CLI tool to the latest version

$ npm install -g @ionic/cli

 

# Create new Ionic application:

Execute the following command to create a new Ionic Angular application with a blank template:

$ ionic start ionic-ng-barcode-demo blank --type=angular

then move to the root path of the application

$ cd ionic-ng-barcode-demo

# Install the Cordova and Ionic Native plugins:

Next, we will install Cordova and Ionic Native plugin wrapper to use Bar Code Scanner and Generator in the application. Run following commands in the terminal at the application root:

$ ionic cordova plugin add phonegap-plugin-barcodescanner
$ npm install @ionic-native/barcode-scanner

# Update Application's App Module

To use Native features, open the app.module.ts file to import the BarcodeScanner class then update providers array as shown below:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule, 
    FormsModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    BarcodeScanner,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Above we have added FormsModule in imports, array to use form elements later.

Also Check: Ionic 4 | Adding Barcode / QR Code Scanner in Ionic 4 Application using ZBar Cordova and Native Plugin

# Implement Barcode/ QR Code Scanner and Generator

The BarcodeScanner class provides two main methods, the scan() is used to scan an Image of Bar or QR code image using the device camera and the encode() method takes the string to convert into a QR code.

For adding configuration, import the BarcodeScannerOptions interface. We will discuss various options available later in this tutorial.

Update the home.page.ts file with the scanBar() and generateBar() methods.

import { Component } from "@angular/core";
import {
  BarcodeScannerOptions,
  BarcodeScanner
} from "@ionic-native/barcode-scanner/ngx";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"]
})
export class HomePage {
  encodeData: any;
  scannedData: {};
  barcodeScannerOptions: BarcodeScannerOptions;

  constructor(private barcodeScanner: BarcodeScanner) {
    this.encodeData = "https://www.FreakyJolly.com";
    //Options
    this.barcodeScannerOptions = {
      showTorchButton: true,
      showFlipCameraButton: true
    };
  }

  scanCode() {
    this.barcodeScanner
      .scan()
      .then(barcodeData => {
        alert("Barcode data " + JSON.stringify(barcodeData));
        this.scannedData = barcodeData;
      })
      .catch(err => {
        console.log("Error", err);
      });
  }

  encodedText() {
    this.barcodeScanner
      .encode(this.barcodeScanner.Encode.TEXT_TYPE, this.encodeData)
      .then(
        encodedData => {
          console.log(encodedData);
          this.encodeData = encodedData;
        },
        err => {
          console.log("Error occured : " + err);
        }
      );
  }
}

The BarcodeScannerOptions defines options like to show torch button, show button to flip camera front or back.

# Update Home Template

Now we will add a button to start scan and show encoded text, also we have added a text field where a user can input a string which can be generated into a QR Code.

In home.page.html, add a button and show the result of scanned Barcode, having text information bar type.

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic QR/ Barcode Scanner
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">
  <h1>Click Button To Scan</h1>

  <ion-button color="primary" (click)="scanBar()">
    Scan Code
  </ion-button>

  <div *ngIf="scannedData">
    <p>
      Scanned Code Text : <b>{{ scannedData["text"] }}</b>
    </p>
    <p>
      Scanned Code Format : <b>{{ scannedData["format"] }}</b>
    </p>
  </div>

  <h1>Enter Value to Create QR code</h1>
  <ion-input placeholder="Enter Input" [(ngModel)]="encodedData"></ion-input>

  <ion-button color="success" (click)="generateBar()">
    Create QR
  </ion-button>
</ion-content>

Now you have a working Bar and QR scanner application which can also generate QR code by taking a user input string.

 

# How to test the application?

To test this application you need to run the app in a real device. Just run following command after connecting your mobile device to the computer via USB wire.

$ ionic cordova run android -l

Note: Sometimes you may see an error like this:

[ERROR] Could not parse build output file: platforms\android\app\build\outputs\apk\debug\output.json

Try creating the app-debug.apk first by running

$ ionic cordova build android

You can generate QR codes online here

See mine 😛

 

Source Code link on GitHub

In this tutorial, we have created a sample app to scan Barcode and QR code using Cordova plugins in Ionic Native.

20 thoughts on “Ionic 5|4 Add Barcode/ QR Code Scanner/ Encoder Generator using Native Plugin”

  1. Jolly, thank you!
    To run this command “ionic cordova build android”, do i need to have installed:
    • Android Studio;
    • Android Studio SDK;
    • Java 8 SDK
    ?

    1. If i remember correctly – you don’t need android studio; just gradle and JDK.
      When you run the command to build; cordova will handle the rest provided that you have set Gradle bin path and JDK bin path into system env.

  2. wow i really love this …Jolly you are the man it actually worked for me when i used the ionic devApp to try….. But my problem is it only shows the number…..how can i get details like the name of the product ,manufacturing date or the expiring date of the product……………..but really its a GoodWork out there….God Bless you…….will be looking forward to hear from you soon

  3. hello, i have a problem, when I scann the code, the app show and alert: barcode data{“text”:”www.facebook.com\n.”,”format”:”QR_CODE”,”cancelled”:false}

    1. Hi Karol, this is the expected behavior to scan and return a response in the JSON object. Can you explain your problem a bit more?

  4. Hello Jolly, I’ve try this project then show the problem about ‘Cannot find module ‘node-sass’ ‘ with npm v 6.8.0. How can I fix this?
    Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top