使ってみようかと思ったら、一発目でできなかったので一応シェアします
今回の問題もanglarのロードタイムの問題で、setTimeoutを使用することでエラーを回避しました
コードはこちらです
全部まとめてあるのでちょっと見にくいかもしれませんが、ご了承ください
肝はchartを表示させるコードの実行時間を送らせてやることです
chartに限らずjQueryでも使ったりするんで、頭の片隅に入れとくと割といい確率で当てはまることがあります
// index.html
// chart.jsを使うことができるようにCDNをネットから引っ張ってきます
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
// app.component.html
<canvas id="myChart" width="400" height="400"></canvas>
//app.component.ts
import {Component, OnInit} from "@angular/core";
declare const Chart: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor() { }
// setitimeがないとロード時間の問題が起きて表示されない
ngOnInit() {
setTimeout(()=>{
this.chart();
}, 500)
}
chart() {
let canvas = <HTMLCanvasElement> document.getElementById('myChart');
let ctx = canvas.getContext("2d");
let myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
参考にした記事

コメントを残す