Meteor + ChartJS

Hi,

I’ve got a problem with ChartJS. I’m trying to print results of the survey to the user, so there are a lots of ‘canvases’ in the template. Drawing charts happens when the template should be ready:

Template.results.onRendered(function () {
var testData = some test data;
var test = document.getElementById(‘test1’).getContext(“2d”);

new Chart(test).Bar(testData);

});

The template looks like this:

<template name="results">
    <div class="container text-center">
        {{#each survey}}
            <canvas id="{{name}}" width="800" height="300"></canvas>
        {{/each}}
    </div>
</template>

But unfortunately I get ‘TypeError: Cannot read property ‘getContext’ of null’ error.

Any ideas?

The issue you have is that onRendered fires when all non-reactive DOM elements are present. As {{#each}} is reactive, those canvas elements will most likely not be there when the results template’s onRendered fires.

You need to instantiate a new template within your {{#each}} loop. That template should contain only the <canvas> element you’ve shown. You then use the onRendered of that template to create the chart.

I hope that makes sense!

3 Likes

Yup, did the trick :slight_smile:

Thanks!

1 Like