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
- How to push element in array in a certain structure
- Thousand separator in pie chart of charts.js
- Destroying the Div and its contents inside the jquery dialog when close button is clicked
- Chart.js line graph-removing labels on the line
- Is it possible to combine two Y axes into a single tooltip with ChartJS 2?
- Array data not rendering in data table using this.props - ReactJS
- ChartJS - Returning labels and data from server on different calls
- How do I customize the chart.js tooltip? Two labels have the same data, which I want to show you with each data
- How do I change the appearance of tooltips with mode: index in Chart.js
- ChartJS, Multiple line in bar chart label
- Manipulate chart.js based plots in R (radarchart)
- Reducing Y-axis in chart.js
- Chart.js Charts not loading until hard refresh [Laravel] [Laravel Charts]
- React and chart.js with json
- How we embed google analytics chart from google analytic with angular 4?
- Chart.js with React
- chart.js line chart update once every 5 seconds?
- Why is chartjs treating these arrays differently?
- Remove zero values from tooltip
- Show values in Chart.js Pie chart parts
- Merge two objects with different keys in chartjs bar
- ChartJS display tooltip at maximum/minimum value
- chart.js streaming data plugin data format or config error
- Chart.JS Chart top left corner is blocked by some visual nodejs
- Alter values of xAxis in chartjs
- How to get rid of the line on top of every point on a line chart (Chart.js)
- Pie chart.js - show all 3 segment borders
- How do you remove the data value from the mouse-over result in radar chart?
- Radar chart - show values near vertices in chart.js
- y=0 gridline (or axis?) not showing in chart.js