Create QR and Barcode Scanner in Ionic 5 Angular

Throughout this quick tutorial, you will understand how to swiftly integrate QR and Barcode scanner in the Ionic 5 Angular application using the barcode scanner plugin.

We will aslo share how to create functionality to scan barcode and how to generate bar codes in ionic app from scratch.

Norman Joseph Woodland invents the barcode, and it is a method of interpreting data in a visual or machine-readable form. In modern era barcode has become the part of our daily lives nowadays Barcodes are referred to products as a means of immediate identification.

In the purchase process, they are playing the vital role. Similarly, they also play a critical role in tracking the inventory, handling invoices, and many more.

Let us try to implement QR or Barcode scanner in Ionic 5 application using the barcode scanner package.

Ionic Native and Cordova registry offers the very awesome Barcode Scanner plugin. It helps open the camera view and automatically scan a barcode; after scanning, it gives back the essential data.

It supports a flawlessly wide array of modern platforms, for instance, Android, BlackBerry 10, Browser, iOS, and Windows.

Build Barcode Scanner in Ionic 5 Angular

  • Step 1: Getting Started
  • Step 2: Install Barcode Scanner Plugin
  • Step 3: Add Plugin into App Module
  • Step 4: Create Barcode Scanner
  • Step 5: Generate Barcode or QR Code
  • Step 6: Final QR/Barcode Scanner Integration
  • Step 7: Start Application

Getting Started

You must have Ionic CLI added to your system to commence the development in Ionic ideally.

npm install -g @ionic/cli

You are now able to install a blank new ionic angular app:

ionic start ionic-barcode-app blank --type=angular

Use command to get into the app folder:

cd ionic-barcode-app

Install Barcode Scanner Plugin

After getting inside the application directory, type all three commands on the command prompt to start installing bar code scanner and ionic native plugins.

ionic cordova plugin add phonegap-plugin-barcodescanner

npm install @ionic-native/barcode-scanner

npm i @ionic-native/core

Add BarcodeScanner into App Module

After adding the QR code plugin into the ionic app, you require to add the barcode scanner into the app module class; this plugin will be available throughout the app, and you can access its methods seamlessly.

Insert code in app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';


// module
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';


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

export class AppModule {}

Create Barcode Scanner

Creating a barcode scanner is simple, head over to TypeScript template and import BarcodeScanner and BarcodeScannerOptions at the top.

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

Inject BarcodeScanner api into the constructor method, declare barcode scanner options, the scanBRcode() method allows scanning the QR code.

export class HomePage {

    encodedData: any;
    scannedBarCode: {};
    barcodeScannerOptions: BarcodeScannerOptions;
  
    constructor(private scanner: BarcodeScanner) {
  
      this.encodedData = "Programming isn't about what you know";
      
      this.barcodeScannerOptions = {
        showTorchButton: true,
        showFlipCameraButton: true
      };
      
    }
  
    scanBRcode() {
      this.scanner.scan().then(res => {
          this.scannedBarCode = res;
        }).catch(err => {
          alert(err);
        });
    }
  
}

Create a button to bind the scan br code method; when the barcode is scanned, it will display the device screen’s output.

<ion-card>
    <ion-button color="danger" (click)="scanBRcode()" expand="block">
        Scan Barcode
    </ion-button>
</ion-card>

<ion-card>
    <div *ngIf="scannedBarCode">
        <ion-item>
            Scanned code output: <strong>{{ scannedBarCode["text"] }}</strong>
        </ion-item>
        <ion-item>
            Scanned code output: <strong>{{ scannedBarCode["format"] }}</strong>
        </ion-item>
    </div>
</ion-card>

You can scan the given below barcode:

Barcode Scanner

This will be the result after scanning the above QR code.

Ionic QR Code example

Generate Bar Code

Similarly, we can generate bar code in ionic using encode() method, you need to update TypeScript and HTML templates of Ionic app. We have added the text for the barcode. However, you can add new text in the input field and click on the generate bar code button to create a new one.

generateBarCode() {
    this.scanner.encode(this.scanner.Encode.TEXT_TYPE, this.encodedData).then(
        res => {
          alert(res);
          this.encodedData = res;
        }, error => {
          alert(error);
        }
    );
}
<ion-card>
    <h3>Generate New QR Code</h3>
    <ion-input placeholder="Enter Input" [(ngModel)]="encodedData"></ion-input>

    <ion-button color="primary" (click)="generateBarCode()" expand="block">
        QR Code Create
    </ion-button>
</ion-card>

Generate Bar Code

Final QR/Barcode Scanner Integration

Here is the final QR/Barcode scanner integration in ionic app. We have combined all the codes you can use to scan QR codes in ionic and generate QR codes in the ionic application.

Place suggested code in home.page.ts file:

import { Component } from '@angular/core';

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

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  encodedData: any;
  scannedBarCode: {};
  barcodeScannerOptions: BarcodeScannerOptions;

  constructor(private scanner: BarcodeScanner) {

    this.encodedData = "Programming isn't about what you know";
    
    this.barcodeScannerOptions = {
      showTorchButton: true,
      showFlipCameraButton: true
    };
    
  }

  scanBRcode() {
    this.scanner.scan().then(res => {
        this.scannedBarCode = res;
      }).catch(err => {
        alert(err);
      });
  }

  generateBarCode() {
    this.scanner.encode(this.scanner.Encode.TEXT_TYPE, this.encodedData).then(
        res => {
          alert(res);
          this.encodedData = res;
        }, error => {
          alert(error);
        }
      );
  }

}

Insert code in home.page.html file:

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

<ion-content [fullscreen]="true">

  <ion-card>
    <ion-button color="danger" (click)="scanBRcode()" expand="block">
      Scan Barcode
    </ion-button>
  </ion-card>

  <ion-card>
    <div *ngIf="scannedBarCode">
      <ion-item>
        Scanned code output: <strong>{{ scannedBarCode["text"] }}</strong>
      </ion-item>
      <ion-item>
        Scanned code output: <strong>{{ scannedBarCode["format"] }}</strong>
      </ion-item>
    </div>
  </ion-card>

  <ion-card>
    <h3>Generate New QR Code</h3>
    <ion-input placeholder="Enter Input" [(ngModel)]="encodedData"></ion-input>

    <ion-button color="primary" (click)="generateBarCode()" expand="block">
      QR Code Create
    </ion-button>
  </ion-card>
</ion-content>

Start Application

We have created the barcode scanner feature now we are only left with testing the feature we created. Hence, you can test the app on the emulator.

So, use command to add the platform for iOS, Android or Windows:

ionic cordova platform add ios

ionic cordova platform add android

ionic cordova platform add windows

Create the ionic app build:

ionic cordova build ios

ionic cordova build android

ionic cordova build windows

Finally, start the application:

ionic cordova run ios -l

ionic cordova run android -l

ionic cordova run windows -l

Conclusion

So this was it, this quick tutorial profoundly gave you details about all the instructions which is predetermined to implement barcode and QR code scanner in ionic app. We hope you will share this tutorial with others to help the development community.