How to use a bar/QR code scanner with Angular

Integrate a hardware QR code, Bare code scanner to your Angular web application without libraries or plugins

Adnane Lamghari
ITNEXT

--

Lately, I had to add a bar code scanner to an Angular application, I tried to look for a plugin (like the ones available on Ionic using the phone camera) or a library that can do that instead of reinventing the path, I found nothing.

In today’s article, I’ll share with you how I managed to integrate the barcode/Qr code reader to my web Angular application easily.

Context :

After a few tests with the barcode scanner I had, I noticed that when I scan a bar code while opening a text editor, my computer / phone started typing the exact same code I’m scanning and at the end, it went to a new line.

Solution :

Basically, the scanner behaved like a keyboard connected to my device; it typed digit by digit of the code, and it added a back to line ‘\n’ at the end.

Let’s see what we can do with that; so I’m gonna add a listener on keypress event using the @HostListner() decorator to receive the code a digit a time and I’ll concatenate it to a string variable; we’ll do that until we receive the back to line '\n’ which means we got the full code 😌

Pro move ?

We may need to scan QR codes in multiple pages in our application, let’s make our solution reusable by creating a class that we can extend whenever we need to scan code in our application.

As we are working on an Angular project, and we love to use hooks, so let’s make a hook-like that gets fired when a QR / Bar code is scanned. Let’s name our class ‘OnScan’ to follow the same pattern as Angular’s core classes (‘OnInit’, ‘OnDestroy’..) :

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

@Component({template: ''})
// tslint:disable-next-line:component-class-suffix
export abstract class OnScan {
private code: string = '';

public abstract onScan(code: string): void;

@HostListener('window:keypress', ['$event'])
protected keyEvent(event: KeyboardEvent): void {
if (event.key === 'Enter') {
this.onScan(this.code);
this.code = '';
} else {
this.code += event.key;
}
}
}

Now when our listener receive the back to line event, we’ll call our ‘hook-like’ function -onScan- to notify our components that our QR code is ready. Obviously, the onScan abstract function should be implemented in every component to be able to use the QR code.

Let’s imagine now that you need to know how many times you scanned a code in a row, we’ll add a counter

And voilà :

Thanks for reading this article 😄

Your feedback and comments are welcome.

--

--