Helo,
you have chartjs installed. You can use it directly
Check in package.json, that you have installed chartjs. You see something like that
"chart.js": "^2.7.3",
If not, install chartjs.
Next to make codeing more comfortable install typings from https://www.npmjs.com/package/@types/chart.js, then you have intellisense. Makes live easier.
npm install --save @types/chart.js
Now you should have in package.json something like
"@types/chart.js": "^2.7.42",
Next step is to use it. Add to your html. The chartcontainer is need for responsibility, otherwise it is not necessary. On chartcanvas is the chart rendered. That is all you need in html. Style with classes on div, canvas whatever you want.
<div #chartContainer class='chart-container'>
<canvas #chartcanvas id="myChart"></canvas>
</div>
Next is import the lib. in your ts.
import { Chart } from 'chart.js';
To fetch a standard html tag like div, canvas, you also need to import childview and ElementRef. More Imports not needed…
import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
Create a variable in your class that will hold your chart. It will be fill later.
myChart: Chart;
Next is to fetch your html tags into a variable with viewchild. You do this inside your class.
@ViewChild('chartContainer') chartcontainer: ElementRef;
@ViewChild('chartcanvas') chartcanvas: ElementRef;
viewchild references are ready in ngAfterViewInit lifecyle
ngAfterViewInit() {
this.createChart();
}
Create and fill your chart with datas like example.
createChart() {
this.myChart = new Chart(this.chartcanvas.nativeElement, {
type: 'horizontalBar',
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: {
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
You are done. If you wanna change datas etc. you can do this like
this.myChart.data = this.yourdata;
this.myChart.config.options = youroptions;
this.myChart.update();
If you need that the dimensions of your chart change, then you change the dimension of chartcontainer before you set the new datas and chart dimensions follow, like
this.chartcontainer.nativeElement.style.height = this.yourheight + 'px';
Best regards, anna-liebt.