Posted at

Angular4 で Chart.js v2 を使う手順

More than 1 year has passed since last update.


雛形を作成

ng new practice-chart.js && cd $_

npm install --save chart.js
ng g component chart


canvas で hello, world

最初に Angular4 で canvas を使う方法を確認します。まず、 描画した後にDOMに対してフォーカスを当てたいので AfterViewInit を使います。また、対象となる canvas 要素を ViewChild アノテーションを使って関連付けを行います。

edit src/app/app.component.ts

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

@Component({
selector: 'app-root',
template: `
<div style="width:800px;height:400px;">
<canvas #myCanvas></canvas>
</div>
`

})

export class AppComponent implements AfterViewInit {

ctx: CanvasRenderingContext2D

@ViewChild('myCanvas') myCanvas

ngAfterViewInit() {
const canvas = this.myCanvas.nativeElement;
this.ctx = canvas.getContext('2d')

this.draw()
}

draw() {
this.ctx.font = "30px Arial"
this.ctx.fillText("Hello World", 10, 50)
}
}

ng serve で動作確認を行います。


Chart.js

create src/app/chart.js

import Chart from 'chart.ts'

export function drawBarChart(ctx) : Chart {
return new Chart(ctx, {
type: 'line',
data: {
labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
datasets: [{
label: 'apples',
lineTension: 0,
data: [12, 19, 3, 17, 6, 3, 7],
borderWidth: 1,
borderColor: "rgba(153,255,51,0.8)",
backgroundColor: "rgba(255,255,255,0)",
}, {
label: 'oranges',
lineTension: 0,
data: [2, 29, 5, 5, 2, 3, 10],
borderWidth: 1,
borderColor: "rgba(255,153,0,0.8)",
backgroundColor: "rgba(255,255,255,0)"
}]
},
});
}

edit src/app/app.component.ts

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

+import { drawBarChart } from './chart'

@Component({
selector: 'app-root',
@@ -23,7 +24,8 @@ export class AppComponent implements AfterViewInit {
}

draw() {
- this.ctx.font = "30px Arial"
- this.ctx.fillText("Hello World", 10, 50)
+ drawBarChart(this.ctx)
}
}


tooltip

tooltip のフォーマットを修正したい場合は以下のように options を追加します

@@ -21,6 +21,24 @@ export function drawBarChart(ctx): Chart {

backgroundColor: "rgba(255,255,255,0)"
}]
},
+ options
});
}

+const options = {
+ tooltips: {
+ enabled: true,
+ mode: 'label',
+ backgroundColor: 'black',
+ caretSize: 5,
+ callbacks: {
+ beforeTitle: (tooltipItem, data) => {
+ return "========="
+ },
+ afterBody: (tooltipItem, data) => {
+ return "test test test test test test"
+ },
+ }
+ }
+}


参考URL