score:54
You can install the package, along with the types for full functionality in a typescript environment such as Angular:
npm install --save chart.js && npm install --save-dev @types/chart.js
Then in your component you can now import * as Chart from 'chart.js'
and use it in your typescript environment. Check out this example for implementation methods using typescript.
Because you need to get the canvas from the DOM you need to make sure it's rendered before attempting to access it. This can be accomplished with AfterViewInit
.
import { Component, AfterViewInit } from '@angular/core';
import * as Chart from 'chart.js'
export class MyChartComponent implements AfterViewInit {
canvas: any;
ctx: any;
ngAfterViewInit() {
this.canvas = document.getElementById('myChart');
this.ctx = this.canvas.getContext('2d');
let myChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: ["New", "In Progress", "On Hold"],
datasets: [{
label: '# of Votes',
data: [1,2,3],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {}
});
}
}
score:1
So, after a lot of thought, I decided to jump in on this thread, b/c there is an Angular way of doing this that follows best practices and doesn't use any document scope querying... (yuck). For brevity's sake, I've used a template
in the Component decorator, not a templateUrl
, but they behave the same as if it were in a template. The DOM still has to e loaded first, and that's the big gotcha with Chart.js. This example is for Angular 8+ and is working with my current version which is 9.1.7
import { Component, ViewChild, AfterViewInit, Input } from '@angular/core'
import { Chart } from 'chart.js'
@Component({
selector: 'app-chart',
template: `<canvas #myChart></canvas>,
})
export class SkillsChartComponent implements AfterViewInit {
@ViewChild('myChart', {
static: true
}) myChart: {
nativeElement: HTMLCanvasElement
}
constructor() {}
ngAfterViewInit() {
this.createChart()
}
private createChart(): void {
const elem = this.myChart.nativeElement
try {
new Chart(elem, {
type: 'pie',
data: {
labels: ["New", "In Progress", "On Hold"],
datasets: [{
label: '# of Votes',
data: [1,2,3],
backgroundColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
responsive: false,
display:true
}
})
} catch (err) {
throw new Error(err) // You can either throw an error or do whatever here...
} finally {
// Any cleanup of logging...
}
}
}
What's going on here is that you're getting a reference to the Canvas itself, and using Angular's lifecycle hooks to say once the HTML content is initialized, then draw onto the canvas using Chart. The fact that the first argument of Chart is the element itself, this leads to a lot of anti-patterns, but you definitely don't need vanilla JS querying the document scope to get a handle on a specific canvas, and this is the best practice way of doing it according to Angular style guides. If you have concerns, leave them in the comments.
score:2
In my Angular 6.1 site, I am using chart.js by itself in mgechev/angular-seed.
As of writing this response, Chart.js developers have some work to do to make exporting its members compliant with newer standards so rollups may be problematic.
To get Chart.js 2.7.x to work after installing package chart.js
and types @types/chart.js
in this angular-seed, all I needed to do is:
Update
project.config.ts
to include ROLLUP_NAMED_EXPORTS to get rollup to work properly (if you're using a rollup).this.ROLLUP_NAMED_EXPORTS = [ ...this.ROLLUP_NAMED_EXPORTS, { 'node_modules/chart.js/src/chart.js': ['Chart'] } ];
Update
project.config.ts
to include additional packages. This seed uses SystemJS config. This might vary if you're using something else.// Add packages const additionalPackages: ExtendPackages[] = [ { name: 'chart.js', path: 'node_modules/chart.js/dist/Chart.bundle.min.js' }, ... ];
In your component
import { Chart } from 'chart.js'; ... export class MyComponent implements OnInit { @ViewChild('myChart') myChartRef: ElementRef; chartObj: Chart; ... }
Then load chart configuration in ngOnInit() per Chart.js documentation
HTML will look something like this:
<div class="chart-container"> <canvas #myChart></canvas> </div>
Source: stackoverflow.com
Related Query
- Extending Existing Chart Types angular chart js using chart js 2.0
- Create multiple dynamic stacked chart using chart.js in Angular 10?
- Show labels on each sector to polar chart using angular js chart
- How to show percentage (%) using chartjs-plugin-labels ( Pie chart ) in angular 2/8
- Using two JSON objects to make Chart.JS Bar Chart Dynamic in Typescript / Angular
- How to send data to chart js using angular
- how to increase space between legend and chart in chartjs (ng2charts ) using angular
- Chart.js chart doesn't render when using Angular 2
- How to display the values inside the pie chart of PrimeNG (chart) using JavaScript or Angular
- Bar Chart in Angular JS Using Chartjs
- How to show symbols after the label and before the numeric value using chart.js Bar chart in Angular
- I am using chart js to draw a chart. I did everything right but i don't know why the x axis and y axis label is not comming in chart. code below
- Building Multiple Charts Using Chart JS in an Angular Application
- How Can I Get An Instance of a ChartJS Bar Chart Using Angular
- How to display Json object in chart js consisting of lists created using Django rest framework in angular application
- How to take data from an API and create a chart on that using Chart.js and Angular 8?
- how to create line chart using chart.js in angular 2+
- Pie chart not working using angular and ng2-charts
- How to run Chart.js samples using source code
- Angular 4: Different color for bar in bar chart dynamically using ChartJS
- How to add text inside the doughnut chart using Chart.js?
- Converting Chart.js canvas chart to image using .toDataUrl() results in blank image
- Moving vertical line when hovering over the chart using chart.js
- create a multi line chart using Chart.js
- Using Chart.js on Angular 4
- How to add an on click event to my Line chart using Chart.js
- Display line chart with connected dots using chartJS
- Dynamically update the options of a chart in chartjs using Javascript
- How to save Chart JS charts as image without black background using blobs and filesaver?
- How to Draw Gantt chart using chart js or other libraries
More Query from same tag
- Chart js different background for y axis
- ng2-chart.js tooltip always showing
- Hide all scale labels in chartjs
- Chart.js - How does it calculate Y-Axis on bar chart?
- angularjs chartjs legend undefined
- Canvas is not defined for simple chart
- Background color does not work when trying to create my data before using scatter chart with chart.js
- Why this Tooltip callback for ChartJS works and this doesn't
- Chart.js set Doughnut background-color?
- Creating a Normal Distribution graph with Chart.js
- Split legend in chart js
- How to define chart.js time scale date formats
- How to add left padding for my charts done in ChartJs and my Google Map so it is not glued to the limit of the page on the left
- Chart.js <frame> or <iframe> elements do not have a title
- How to hide the legend display for a specific chart?
- Stacked Floating Horizontal Bar using ChartJS
- ChartJs - Double tooltip Top and Bottom on hover
- Chart.js how to modify an existing legend
- Chartjs Bar Chart showing old data when hovering when use of ajax
- Apply/Register conflicting plugins to different charts
- Chart.js How to make a sample math axis?
- Multiple add in multiple sql request?
- chart.js number of labels equal to number of datapoints
- Chart.js: width and height of a pie chart not respected
- How to show percentage (%) using chartjs-plugin-labels ( Pie chart ) in angular 2/8
- Chart.js responsive pie chart
- Why is the data from my API not displaying on my chart.js chart in React?
- ChartJS 2.6 - Bar chart fixed height scrollable-X
- Getting access to already created Chart.js chart
- Django show Graphs with ChartJS