BadaBoomphs
BadaBoomphs

Reputation: 59

How do I implement zingchart into angular2

I have an existing project that I want to implement zingcharts on.

I have tried 3 different tutorials mainly from " https://blog.zingchart.com/2016/07/19/zingchart-and-angular-2-charts-back-at-it-again/ "blog.

However I can not get that working in my project. So I decided I will try and implement it the most basic way first and later on try better ways. This is what I did but it does not shop up yet.

Being new to angular2 I am not quite sure if this will work.

I went to the ZingChart website and tried to implement this basic example ->https://www.zingchart.com/docs/getting-started/your-first-chart/

So I built 2 files chart.ts and chart.component.html and implemented the

"<script src="https://cdn.zingchart.com/zingchart.min.js"></script>"

in the index.html

//chart.ts

import { Component } from '@angular/core';

@Component({
    selector: 'rt-chart',
    templateUrl: './chart.component.html'

})

export class Chart
{

}

//chart.component.html

<!--Chart Placement[2]-->
  <div id="chartDiv"></div>
  <script>
    var chartData = {
      type: "bar",  // Specify your chart type here.
      title: {
        text: "My First Chart" // Adds a title to your chart
      },
      legend: {}, // Creates an interactive legend
      series: [  // Insert your series data here.
          { values: [35, 42, 67, 89]},
          { values: [28, 40, 39, 36]}
  ]
};
zingchart.render({ // Render Method[3]
  id: "chartDiv",
  data: chartData,
  height: 400,
  width: 600
});
  </script>

I called it in my already working website as

It does not show up. What am I doing wrong? Is there something I am missing. Angular2 is quite new to me.

Thanks

Upvotes: 3

Views: 1240

Answers (1)

yurzui
yurzui

Reputation: 214175

With latest angular2 version (@2.2.3) you can leverage special ZingChart directive like this:

zing-chart.directive.ts

declare var zingchart: any;

@Directive({
  selector : 'zing-chart'
})
export class ZingChartDirective implements AfterViewInit, OnDestroy {
  @Input()
  chart : ZingChartModel;

  @HostBinding('id') 
  get something() { 
    return this.chart.id; 
  }

  constructor(private zone: NgZone) {}

  ngAfterViewInit() {
    this.zone.runOutsideAngular(() => {
      zingchart.render({
        id : this.chart.id,
        data : this.chart.data,
        width : this.chart.width,
        height: this.chart.height
      });
    });
  }

  ngOnDestroy() {
    zingchart.exec(this.chart.id, 'destroy');
  }
}

where ZingChartModel is just a model of your chart:

zing-chart.model.ts

export class ZingChartModel { 
  id: String;
  data: Object;
  height: any;
  width: any;
  constructor(config: Object) {
    this.id = config['id'];
    this.data = config['data'];
    this.height = config['height'] || 300;
    this.width = config['width'] || 600;
  }
}

Here's completed Plunker Example

Upvotes: 5

Related Questions