2๐
โ
you can use @ViewChild decorator to query an element from component template
BarChartComponet
@ViewChild('chartElm', { static: true }) public chartElm: ElementRef;
ngAfterViewInit() {
this.addchart();
}
public addchart(){
var canvas = <HTMLCanvasElement> this.chartElm.nativeElement; // ๐
var ctx = canvas.getContext("2d");
var mychart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue'],
datasets: [{
label: '# of Votes',
data: [12, 19],
backgroundColor: 'lightgreen',
borderColor: 'blue',
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
}
});
}
template
<div style="width:400px; height:100%;">
<canvas #chartElm ></canvas>
</div>
Source:stackexchange.com