I am currently trying to implement a Object[] instead of an Primitive[] for the data set in Chartjs. I'm using Angular in combination with Chart.js 3.6.0 and ng2-charts 3.0.0-rc.7
line-chart.component.ts:
import { ChartConfiguration, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import * as moment from "moment";
@Component({
selector: 'app-line-chart',
templateUrl: './line-chart.component.html',
styleUrls: ['./line-chart.component.scss']
})
export class LineChartComponent implements OnInit {
....
public lineChartData: ChartConfiguration['data'] = {
datasets: [
{
data: [
{x: '2021', y: 12}, > TS2322: Type 'string' is not assignable to type 'number'.
],
label: 'FBSV',
}
],
// empty for for dynamic structuring.
labels: []
};
public lineChartOptions: ChartConfiguration['options'] = {
plugins: {
title: {
display: true,
text: this.title,
color: '#25167A',
font: {
size: 15,
weight: 'bold'
}
},
},
elements: {
line: {
tension: 0.25 // creates smoother lines
}
},
scales: {
x: {
display: true,
title: {
display: true,
text: 'Year',
color: '#25167A',
font: {
size: 15,
weight: 'bold'
}
},
type: 'time',
time: {
unit: 'year'
}
},
y: {
display: true,
title: {
display: true,
text: 'Score',
color: '#25167A',
font: {
size: 15,
weight: 'bold'
}
},
max: 100,
min: 0,
beginAtZero: true
}
}
};
public lineChartType: ChartType = 'line';
@ViewChild(BaseChartDirective) chart?: BaseChartDirective;
....
The problem is that in the Chart.js 3.6.0 docs it states that you should be able to use non primative data values: https://www.chartjs.org/docs/latest/general/data-structures.html
line-chart.component.html:
<canvas baseChart
[data]="lineChartData"
[options]="lineChartOptions"
[type]="lineChartType">
</canvas>
How can I fix this in order to be able to use dates in the x value?
CodePudding user response:
You can pass your own type to the ChartConfiguration
interface as a second parameter like so:
const lineChartData: ChartConfiguration<"line", { x: string, y: number }[]> = {
type: "line",
data: {
labels: [],
datasets: [
{
data: [
{ x: "test", y: 55 },
{ x: "hi", y: 20 },
],
},
],
},
};