angular-chartjs
angular-chartjs copied to clipboard
Failed to create chart: can't acquire context from the given item
For anyone who has an issue with angular 5 and canvas, you have to do it like this:
Html:
<div *ngIf="chart">
<canvas #myCanvas>{{ chart }}</canvas>
</div>
Use viewchild for angular, don't use js getelementbyid:
@ViewChild('myCanvas') myCanvas: ElementRef;
public context: CanvasRenderingContext2D;
Method inside component:
gettest(): void{
this.weatherApi
.dailyForecast()
.subscribe(res => {
let temp_max = res['list'].map(res => res.main.temp_max);
let temp_min = res['list'].map(res => res.main.temp_min);
let alldates = res['list'].map(res => res.dt)
let weatherDates = []
alldates.forEach((res) => {
let jsdate = new Date(res * 1000)
weatherDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
})
this.context = (<HTMLCanvasElement>this.myCanvas.nativeElement).getContext('2d');
this.chart = new Chart(this.context, {
type: 'line',
data: {
labels: weatherDates,
datasets: [
{
data: temp_max,
borderColor: "#3cba9f",
fill: false
},
{
data: temp_min,
borderColor: "#ffcc00",
fill: false
},
]
},
options: {
legend: {
display: false
},
scales: {
xAxes: [{
display: true
}],
yAxes: [{
display: true
}],
}
}
});
})
as you can see you have to properly access context. also initialization of this should be in:
ngAfterViewInit() {
this.gettest();
}
Great! It worked. But it throws this error: ChartsComponent.html:1 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: '. Current value: 'ngIf: [object Object]'. at viewDebugError (core.js:7393) at expressionChangedAfterItHasBeenCheckedError (core.js:7381) at checkBindingNoChanges (core.js:7483) at checkNoChangesNodeInline (core.js:10344) at checkNoChangesNode (core.js:10333) at debugCheckNoChangesNode (core.js:10936) at debugCheckDirectivesFn (core.js:10864) at Object.eval [as updateDirectives] (ChartsComponent.html:1) at Object.debugUpdateDirectives [as updateDirectives] (core.js:10853) at checkNoChangesView (core.js:10232)
Just remove that from div declartion *ngIf="chart"
also if you have blinks or render problems try to make different component and call it inside your main component. it works better
This is used to create graphs dynamically?, i mean, I have some data and I have to create graphs for every iteration I do in a cycle.
I m not facing error after applying the given above changes, but there is no chart visible on page
I've changed the code in template and errors stopped showing up. Chart is ok:
<div>
<canvas #myCanvas></canvas>
</div>
In my case, I was using ngIf on canvas and then I moved it to its parent div. In both cases I was getting this error: chart.js Failed to create chart: can't acquire context from the given item.
So I changed ngIf to ngStyle with display: (condition)? none: block. And it worked for me
wow, great job, this solved my 2 days of efforts in 10 mins, thanks you so much
If anyone else gets this same issue and is searching for the cause, bare this in mind: if using standard JS rather than JQuery the <SCRIPT>
tag containing the chartJS elements must be loaded AFTER the HTML canvas elements to which they refer.