Ng2-charts: Chart object?

Created on 1 May 2017  路  5Comments  路  Source: valor-software/ng2-charts

Maybe its me who doesn't get it, but how do I access the chart object itself. e.g.
from chart.js, one declares new chart:
var myChart = new Chart(ctx, config); // or something like that and then I have myChart object which has many useful methods, such as update or destroy. It seems so trivial, and yet not.

Most helpful comment

@jasonburrows what you mentioned, that you can do with the other library, is an Angular 2 feature, not a that-library-specific feature, so you can do the same with this library.

With this library you have to do this:

In your view:

<canvas baseChart #myChart="base-chart"></canvas>

In your component:

import { ViewChild } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';

class MyComponent {

  @ViewChild('myChart')
  myChart: BaseChartDirective;

}

Then you'll be able to access the ChartJS instance with this.myChart.chart

All 5 comments

I think this works. Correct me if i'm wrong

import { Component, ViewChild } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';

export class Component{
@ViewChild(BaseChartDirective) chart: BaseChartDirective;

How would you do it if you had multiple charts? I was using a different chart.js wrapper (angular2-chartjs and there it was easy - you'd give the chart element a reference name (<chart #myChart ....></chart>) and then reference it in your component like: @ViewChild('myChart') myChart;

To be honest that other angular wrapper has fewer problems than this one even though it is much simpler. I don't have to pass an empty array to colors when I'm providing the color information in the dataset for doughnut charts, for example. I was migrating over as this on seems more maintained, but so far it hasn't been an improvement.

@jasonburrows what you mentioned, that you can do with the other library, is an Angular 2 feature, not a that-library-specific feature, so you can do the same with this library.

With this library you have to do this:

In your view:

<canvas baseChart #myChart="base-chart"></canvas>

In your component:

import { ViewChild } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';

class MyComponent {

  @ViewChild('myChart')
  myChart: BaseChartDirective;

}

Then you'll be able to access the ChartJS instance with this.myChart.chart

@Parziphal thank you so much!

Small update for someone who stumbles here...
ng2-charts ^2.3.0

import { BaseChartDirective } from 'ng2-charts

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dj-techs picture dj-techs  路  3Comments

brandonreid picture brandonreid  路  3Comments

vmironovs picture vmironovs  路  3Comments

egervari picture egervari  路  4Comments

raychenfj picture raychenfj  路  3Comments