import { Component, OnInit, Input, ChangeDetectionStrategy, ElementRef, Inject, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core'; import QRCode from 'qrcode'; import { DOCUMENT } from '@angular/platform-browser'; @Component({ selector: 'na-qrcode', templateUrl: './na-qrcode.component.html', styleUrls: ['./na-qrcode.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class NaQRCodeComponent implements OnInit, OnChanges { @Input() version: number; @Input() data: string; @Input() url: string; @Output() urlChange = new EventEmitter(); @Input() level: 'low' | 'medium' | 'quartile' | 'high' | 'L' | 'M' | 'Q' | 'H' = 'M'; /** * 定义周边区域应该有多宽。 */ @Input() margin = 0; @Input() type: 'image/png' | 'image/jpeg' | 'image/webp' = 'image/jpeg'; /** * Height/Width */ @Input() size = 256; // /** // * 宽度 // */ // @Input() width = 256; // /** // * 高度 // */ // @Input() height: number; /** * 前景色,值必须为十六进制格式(RGBA) */ @Input() colorDark = '#000000'; /** * 背景色,值必须为十六进制格式(RGBA) */ @Input() colorLight = '#ffffff'; constructor(private el: ElementRef, @Inject(DOCUMENT) private _doc: any) { } ngOnInit() { QRCode.toDataURL(this._doc.getElementById('canvas'), this.data, { version: this.version, errorCorrectionLevel: this.level, margin: this.margin, width: this.size, color: { dark: this.colorDark, light: this.colorLight }, type: this.type, rendererOpts: { quality: 0.3 } }) .then(url => { this.urlChange.emit(url); }) .catch(err => { console.error(err); }); } ngOnChanges(changes: SimpleChanges) { const data = changes['data']; if (data && this.isValidQrCodeText(data.currentValue)) { // console.log(data.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'); } }