First, you'll need to install the Chart.js library:
npm install chart.js --save
Next, import the module in your Component:
import { Chart } from 'chart.js';
Prepare your dataTo render your chart, each dataset should be an array of numbers, or an array of objects formatted like the below, where x
and y
refer to the axes of the chart:
[{
x: 1,
y: 10
},{
x: 2,
y: 20
}]
You can substitute the x
or y
properties with t
if you're using the time scale. Use the Array.map() methodto structure your data for Chart.js.
You can also specify labels for the x axis - this must also be an array.
The templateIn your Component's template, add a canvas
element with a reference variableof your choice. Inside the canvas element, bind to the variable chart
. We'll create the variable in the next step.
<canvas #lineChart>{{ chart }}</canvas>
Configuring the chartBack in your Component, import ViewChild
from angular core and add the reference to your canvas element as a private member. Then, add a public variable chart
- this will be assigned to a Chart.js instance and will be binded to our template:
import
@Component({
...
})
export class myComponent implements OnInit {
@ViewChild('lineChart') private chartRef;
chart: any;
...
}
Now that you have your data prepared, and a reference to your canvas element, let's add the basic Chart.js configuration for a line chart with the code below labeled `Chart.js`
Notice that the data.datasets
option takes an array - you can have many datasets displaying on the same line chart.
The chart will now display on your page. If you want to fit your chart into a container, you can set the maintainAspectRatio
option to false. See the Chart.js documentationfor more configuration options!
Comments