Dovev Hefetz Dovev Hefetz - 1 year ago 150
TypeScript Question

How to update the data in an ng2-chartjs2 chart in Angular2 and NodeJS

I am using NodeJS, Angular2, and the ng2-chartjs2. Below I listed the relevant parts of my code that is rendering charts. The data is loaded into from an API using a fixed date range. I would like to allow the user to select a date range and then update the chart. From here I know that you can call update() on the chart object to update the data in it, but I don't know how to get a hold of the chart object, since the component code never actually has a reference to it - it's done automagically when the template is rendered. Looking at the source code (line 13) I see that the author intended to make the object available. I contacted the author but haven't received a response yet and need to get moving. I have learned a lot about Angular2 but am no expert yet, so perhaps a deeper understanding of Angular2 makes this obvious. How can I either get access to the object to call update() on it, or do it some other clean way?

The template contains

<chart [options]="simple.options"></chart>

and the component typescript code contains

import { ChartComponent } from 'ng2-chartjs2';

selector: 'home',
templateUrl: 'client/components/home/home.component.html',
styleUrls: ['client/components/home/home.component.css'],
directives: [DashboardLayoutComponent, CORE_DIRECTIVES, ChartComponent],
pipes: [AddCommasPipe],


setCurrentSimpleChart = (simpleType: number): void => {
this.simple.options = {
type: 'line',
options: this.globalOptions,
data: {
datasets: [{
label: this.titles[simpleType],
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1


Answer Source

You can hold reference to component by using ViewChild:

@ViewChild(ChartComponent) chartComp;

And then you can get chart object:

let chart = this.chartComp.chart;

Here is the corresponding plunker