Radoslav Stoyanov
Radoslav Stoyanov

Reputation: 1780

Angular2 + Chart.js and ng2-charts. Data binding not working as expected

I'm trying to implement Chart.js into my Angular2 application. I'm using ng2-charts directives, too. I set everything as shown in the examples and when I run the app with the sample data everything is ok. The problem comes when I try with my own data. The actual problem is that I'm using a service to load the data within a ngOnInit() method and this way the chart directive is initialized before I have the data (or I guess so). I'm getting this not very descriptive error:

"EXCEPTION: TypeError: t is undefined in [barChartOptions in trafficComponent@6:16]"

It doesn't really say much :) The problem is not in the barChartOptions because I'm replacing only the barChartLabels and barChartData parameters, the rest parameters are as in the example. My parameters are also correct and valid and they are not the problem, too.
I'm wondering if there is a way for reloading (re-initializing) the directive with some Promise-like solution or taking advantage of the lifecycle hooks.
I'll be VERY glad if there is anyone else who has ever faced the same problem and is ready to share his solution :)

Update

I logged in the console the data object passed to the Chart constructor as new Chart(ctx).Bar(data, options); and the labels and datasets.data properties are undefined although I logged them one more time right after I got the data from the service and there they were correct. I think that some kind of data binding should do the trick but I don't know how to achieve it in this case. Actually there is a data binding (as shown in the examples in ng2-charts) but it doesn't work as I expect. Changing properties in my component doesn't affect the properties of the Charts directive and they remain undefined.

Update 2 (2016-02-19)

After updating to the newly released Angular version 2.0.0-beta.7 everything is working as expected.

Upvotes: 1

Views: 4728

Answers (2)

Radoslav Stoyanov
Radoslav Stoyanov

Reputation: 1780

Updating to Angular 2.0.0-beta.7 solves the problem.

Upvotes: 0

Beau Costoff
Beau Costoff

Reputation: 121

I had a similar issue with using chart.js when trying to create a line graph. All my data was showing as undefined. Not sure if your issue is the exact same as mine, but I can at least point you in the direction of my solution which was to use the Dynamic Component Loader.

Chart.js not showing in Angular2 if it doesn't exist on the main page

Upvotes: 1

Related Questions