LoginSignup
6
5

More than 5 years have passed since last update.

Angular7でQRコードを表示したい

Posted at

はじめに

Angular7でQRコードを画面上に描画します。

環境

  • angular 7
  • etc...

利用パッケージ

angular2-qrcode
https://github.com/SuperiorJT/angular2-qrcode

手順

前準備

angular cli を利用してプロジェクトを作成します。
自分はWebStormを使っているので、メニューからNewProject - Angular CLI を選択して作成しました。

angular2-qrcode の導入

基本的にReadme.mdのガイダンス通りです。
https://github.com/SuperiorJT/angular2-qrcode

npm install angular2-qrcode

別の話題ですが、最近は--saveと書く必要はなくなったんですね。
自動でPackage.jsonが更新されるとのこと。
https://qiita.com/glhfdev/items/c5beda8572aa8c1e6be6

なんかエラー出た!!

で、上のコマンドを実行するとインストールされますがエラーが出ます。

./util/has_lib.sh: line 31: pkg-config: command not found
gyp: Call to './util/has_lib.sh freetype' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error 
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:345:16)
gyp ERR! stack     at ChildProcess.emit (events.js:182:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:12)
gyp ERR! System Darwin 16.7.0
以下略

これもReadme.mdに下記のように

Feel free to ignore it.

無視してくださいと書いてあるので無視します。

モジュールに追加する

app.module.tsに今回追加したパッケージモジュールを追加します。
(ここら辺の手順はお決まりですね)

app.module.ts
import {QRCodeModule} from 'angular2-qrcode'; // <-- 追加

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    QRCodeModule   // <-- 追加
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

とりあえず表示してみる

HTMLテンプレートにタグ追加

これもReadme.md通り...

app.component.html
<div>
  <qr-code [value]="'Hello QR code!!'" [size]="150"></qr-code>
</div>

できた!

非常に簡単。
スクリーンショット 2019-02-13 23.26.04.png

Canvasに出力

初期設定だとimgとして描画されています。
スクリーンショット 2019-02-13 23.28.57.png

オプションでcanvas="true"を指定することでcanvasに描画されるようになります。

<div>
  <qr-code [value]="'Hello QR code!!'" [size]="150" canvas="true"></qr-code>
</div>

↑こうすると、こうなる↓
スクリーンショット 2019-02-13 23.32.29.png

最後に

非常に簡単にQRコードを描画することができました。
スマホ決済などで最近一段と馴染みが出てきた感があるQRコード、ちょっとアプリ加えたい時などにどうぞ。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5