In a previous post we have already discussed the most used QR Code and Barcode Scanner Native plugin for IOnic Application, but today we will use another very popular native plugin based on ZBar library.
This is a very good plugin to scan a variety of Barcode types including EAN-13/UPC-A, UPC-E, EAN-8, Code 128, Code 39, Interleaved 2 of 5 and QR Code
Let’s discuss implementation
Create a new Ionic 4 Application
$ ionic start Ionic4ZBarScanner blank
$ cd Ionic4ZBarScanner
Add Cordova and Ionic Nativ pluginÂ
$ ionic cordova plugin add cordova-plugin-cszbar
$ npm install @ionic-native/zbar
Next, we need to include the plugin in the app’s main module file. Replace the following 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 { 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 { ZBar } from '@ionic-native/zbar/ngx'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule], providers: [ StatusBar, SplashScreen, ZBar, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}
Now in the Home page, we will add a button to call scan method and add scan method in home component file home.page.ts file
import { Component } from '@angular/core'; import { ZBar, ZBarOptions } from '@ionic-native/zbar/ngx'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { zbarOptions:any; scannedResult:any; constructor( private zbar: ZBar ) { this.zbarOptions = { flash: 'off', drawSight: false } } scanCode(){ this.zbar.scan(this.zbarOptions) .then(result => { console.log(result); // Scanned code this.scannedResult = result; }) .catch(error => { alert(error); // Error message }); } }
home.page.html
<ion-header>
<ion-toolbar>
<ion-title>
Ionic 4 Barcode/ QR Code Scanner using ZBar
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-button (click)="scanCode()">Scan Code</ion-button>
<p>{{scannedResult}}</p>
</ion-content>
Now you have added a Barcode scanner in Ionic 4 Application using ZBar native plugin. This will only work in the real device. Run $ ionic cordova run android –device command to check in USB connected the real device.
Also See:Â Ionic 4 | Add Barcode/ QR Code Scanner/ Encoder Generator Ionic 4 Native Plugin
Leave a Reply