1π
3 things:
First you define chart as an empty array and then you try to override it with an object. Angular does not like this because it expects an array. So you either need to push it to the array or define it otherwise.
Second, in your html you only render the canvas once the chart variable is set. This does not work afaik since chart.js needs the canvas to create the chart.
Third, your config is in V2 format thats why you also get ts errors on it. Updating to V3 solves that issue. For all changes between V2 and V3 you can read the migration guide.
ngOnInit(): void {
new Chart('canvas', {
type: 'line',
data: {
labels: [],
datasets: [
{
data: [],
borderColor: '#3cba9f',
fill: false,
},
{
data: [],
borderColor: '#ffcc00',
fill: false,
},
],
},
options: {
plugins: {
legend: {
display: false,
},
},
scales: {
x: {
ticks: {
display: true,
},
},
y: {
ticks: {
display: true,
},
},
},
},
});
}
<canvas id="canvas"></canvas>
Stakcblitz: https://stackblitz.com/edit/angular-ivy-t8gqyk?file=src%2Fapp%2Fapp.component.html
- Chartjs-Always show doughnut Chart tooltip in Angular 5
- Chartjs-Creating a Custom Point Element In Chart JS
0π
I think your scales are incorrect. That may be whatβs causing the error. Try changing
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}]
}
}
to:
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
ticks: {
display: true
}
}
],
xAxes: [
{
ticks: {
display: true
}
}
]
}
}
0π
There were a number of things I corrected. I referenced the ChartJS docs and got the canvas tag a different way than you did.
<canvas id="lineChart"></canvas>
import { Component, VERSION } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
chart: any;
ngAfterViewInit() {
let ctx: any = document.getElementById("lineChart") as HTMLElement;
var data = {
labels: ["match1", "match2", "match3", "match4", "match5"],
datasets: [
{
label: "TeamA Score",
data: [10, 50, 25, 70, 40],
backgroundColor: "blue",
borderColor: "lightblue",
fill: false,
lineTension: 0,
radius: 5
},
{
label: "TeamB Score",
data: [20, 35, 40, 60, 50],
backgroundColor: "green",
borderColor: "lightgreen",
fill: false,
lineTension: 0,
radius: 5
}
]
};
//options
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "Line Graph",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#333",
fontSize: 16
}
}
};
//create Chart class object
var chart = new Chart(ctx, {
type: "line",
data: data,
options: options
});
}
}