I'm working on an Angular dashboard development and I found this error that doesn't let me render area chart
import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
selector: 'app-widget-area',
templateUrl: './area.component.html',
styleUrls: ['./area.component.scss']
})
export class AreaComponent implements AfterViewInit {
constructor() {}
ngAfterViewInit() {
let elem: HTMLElement;
const ctx = document.getElementById("myChart") as HTMLElement;
if (ctx) {
elem = ctx;
const myChart = new Chart(elem, {
data: {
datasets: [
{ fill: 'origin' }, // 0: fill to 'origin'
{ fill: '+2' }, // 1: fill to dataset 3
{ fill: 1 }, // 2: fill to dataset 1
{ fill: false }, // 3: no fill
{ fill: '-2' }, // 4: fill to dataset 2
{ fill: { value: 25 } } // 5: fill to axis value 25
]
}
});
}
}
And got this error:
TS2345: Argument of type 'HTMLElement' is not assignable to parameter of type 'ChartItem'.
Type 'HTMLElement' is missing the following properties from type 'HTMLCanvasElement': height, width, captureStream, getContext, and 2 more.
I've tried with all the internet stuff and nothing worked for me, anyone have the same error? BTW this is my simply html, I have my NgChartModule from charjs and nothing worked for me
<div>
<div style="display: block">
<canvas id="myChart " ></canvas>
</div>
</div>
Chart
class' constructor take the first parameter (item
) as ChartItem
type where ChartItem
takes type of:
ChartItem: string | CanvasRenderingContext2D | HTMLCanvasElement | { canvas: HTMLCanvasElement } | ArrayLike<CanvasRenderingContext2D | HTMLCanvasElement>
From here, you can see the usage:
const ctx = document.getElementById('myChart');
const ctx = document.getElementById('myChart').getContext('2d');
const ctx = $('#myChart');
const ctx = 'myChart';
const ctx = document.getElementById("myChart");
if (ctx) {
const myChart = new Chart(ctx, {
data: {
datasets: [
{ fill: 'origin' }, // 0: fill to 'origin'
{ fill: '+2' }, // 1: fill to dataset 3
{ fill: 1 }, // 2: fill to dataset 1
{ fill: false }, // 3: no fill
{ fill: '-2' }, // 4: fill to dataset 2
{ fill: { value: 25 } } // 5: fill to axis value 25
]
}
});
}