Reputation: 91
I have a problem with chart.js and angular2. Nothing is display when I try to bind a chart to a canvas(inside an angular template). Outside of angular everything works fine. My StatisticComponent is included by a router (router-outlet).
component:
@Component({
selector: 'statistic',
templateUrl: 'views/statistic.component.html'
})
class ChartComponent implements AfterViewInit {
@ViewChild('canvas') canvasElement;
ngAfterViewInit() {
var ctx = document.getElementById('canvas');
//var ctx = this.canvasElement.nativeElement;
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
template:
<h2>Statistic</h2>
<canvas #canvas id="canvas"></canvas>
when i set a timeout and reference to a global html canvas(not inside a template) then everything works.
i found one similar post: chart does not display in angular2 component
but this didnt helped. I do not use a systemjs as loader, i use browserify. Hope someone can help.
//UPDATE
//THIS WORKS //APPEND NEW ELEMENT
class ChartComponent implements AfterViewInit {
@ViewChild('container') containerElement;
ngAfterViewInit() {
var canvas = document.createElement('canvas');
this.containerElement.nativeElement.appendChild(canvas);
var myChart = new Chart(canvas, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
//THIS DOES NOT WORK - WHY? //USING VIEWCHILD DIRECTLY
class ChartComponent implements AfterViewInit {
@ViewChild('canvas') canvas;
ngAfterViewInit() {
var myChart = new Chart(this.canvas.nativeElement, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
Upvotes: 2
Views: 668
Reputation: 91
Try updating your template and wrap your canvas-element inside a div. Don't know the cause to it but the problem seems to appear when the canvas-element is at the root of the template html.
Updated template:
<h2>Statistic</h2>
<div>
<canvas #canvas id="canvas"></canvas>
</div>
Upvotes: 9
Reputation: 6430
Have you considered looking into an existing adaptation to ChartJs with Angular2. For example ng2-charts is a great alternative that you might be able to utilize that makes it easier to incorporate into your angular2 app.
Upvotes: 0