angularx-qrcode
Version:
Ionic 3/4 and Angular4/5/6/7/8+ QRCode module generator using qrcodejs
90 lines (75 loc) • 2.16 kB
text/typescript
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
Inject,
Input,
OnChanges,
PLATFORM_ID,
SimpleChange,
} from '@angular/core';
import { isPlatformServer } from '@angular/common';
declare var require: any;
let QRCode: any;
export class QRCodeComponent implements OnChanges, AfterViewInit {
/** @internal */
public allowEmptyString: boolean = false;
public colordark: string = '#000000';
public colorlight: string = '#ffffff';
public level: string = 'M';
public hidetitle: boolean = false;
public qrdata: string = '';
public size: number = 256;
public usesvg: boolean = false;
public qrcode: any;
constructor(
public el: ElementRef,
private readonly platformId: any,
) { }
public ngAfterViewInit() {
if (isPlatformServer(this.platformId)) {
return;
}
if (!QRCode) {
QRCode = require('qrcodejs2');
}
try {
if (!this.isValidQrCodeText(this.qrdata)) {
throw new Error('Empty QR Code data');
}
this.qrcode = new QRCode(this.el.nativeElement, {
colorDark: this.colordark,
colorLight: this.colorlight,
correctLevel: QRCode.CorrectLevel[this.level.toString()],
height: this.size,
text: this.qrdata || ' ',
useSVG: this.usesvg,
width: this.size,
});
} catch (e) {
console.error('Error generating QR Code: ' + e.message);
}
}
public ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
if (!this.qrcode) {
return;
}
const qrData = changes['qrdata'];
if (qrData && this.isValidQrCodeText(qrData.currentValue)) {
this.qrcode.clear();
this.qrcode.makeCode(qrData.currentValue);
}
}
protected isValidQrCodeText = (data: string): boolean => {
if (this.allowEmptyString === false) {
return !(typeof data === 'undefined' || data === '');
}
return !(typeof data === 'undefined');
}
}