想要在angular2及以上生成二维码的方法有很多,我写我实验过并成功的来分享给大家。一种是直接使用qrcode.js;另外可以使用angular封装好的库,一个是angular2-qrcode(不支持中文),一个是ng2-qrcode

1、qrcode.js

下载

大家可以在这个地址http://davidshimjs.github.io/qrcodejs/去下载qrcode.js,然后将它放到你项目的assets文件夹下。如下图:
assets

使用

先将qrcode.js在你的index.html引入,如下:

index.html
  • html
1
<script type="text/javascript" src="./assets/qrcode/qrcode.min.js"></script>

然后在你需要用到的组件中先要声明(一定要声明,不然会报错),如下:

code.component.ts
  • ts
1
declare var QRCode;

DOM 结构:
code.component.html
  • html
1
<div class="qrcode" id="qrcode"></div>

code.component.ts:
记住,一定要在视图加载完成后在使用,不然它会报错说找不到这个节点,所以一定要写在ngAfterViewInit里。
code.component.ts
  • ts
1
2
3
4
5
6
7
8
9
10
11
import {Component, OnInit, AfterViewInit } from '@angular/core';

export class CodeComponent implements OnInit, AfterViewInit {

ngAfterViewInit() {
new QRCode(document.getElementById('qrcode'), {
width: 150,
height: 150
}).makeCode('this is your content');
}
}

*注:qrcode 还有很多参数,大家可以参考这个http://code.ciaoca.com/javascript/qrcode/

2、angular2-qrcode

下载

在项目中打开“终端”,运行以下命令:

1
npm install angular2-qrcode --save

使用

使用angular2-qrcode首先需要在使用到的模块中引用注册:

code.component.ts
  • ts
1
2
3
4
5
6
7
8
9
10
11
import { NgModule } from '@angular/core';
import { QRCodeModule } from 'angular2-qrcode';
...

@NgModule({
imports: [
QRCodeModule,
...
],
...
})

然后便可以在需要的html页面中使用了:

code.component.html
  • html
1
2
3
<div>
<qr-code [value]="'All QR Code data goes here!'" [size]="150"></qr-code>
</div>

参数说明

参数名 参数类型 参数说明
data String 要转成二维码的文字
size Number 要转成的二维码图片的大小
level String 要转成的二维码的质量等级(’L’, ‘M’, ‘Q’, ‘H’)(可以为空)
type Number 要转成二维码的文字对应的缓冲区的大小(可以为空

*注:
二维码的质量等级指的是二维码的容错率:

  • L:容错率7%
  • M:容错率15%
  • Q:容错率25%
  • H:容错率30%

** 注:我实验ng2-qrcode失败了,照着官方文档也没有弄出来,等后面我实验出来了再来告诉大家~