Angular 6 Chartist Donut Chart not getting load on first time when getting data from api

4.5k views Asked by At

"I am using Angular 6. I have a donut chart on dashboard its data doesn't get load on first time , when i go to some other page and come back donut chart displays. On refresh also data disappears. I am getting api data with help of resolver. Graph and other components gets loaded but not this chart. It works completely fine when given static data."

import { Component, OnInit } from '@angular/core';
import * as Chartist from 'chartist';
import { ChartType, ChartEvent } from "ng-chartist/dist/chartist.component";
import { ActivatedRoute } from '@angular/router';

var obtained: any

export interface Chart {
  type: ChartType;
  data: Chartist.IChartistData;
  options?: any;
  responsiveOptions?: any;
  events?: ChartEvent;
}

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

    total: any
    obtained: any
    public dataApi: any;       

  constructor(private route:ActivatedRoute) {          
  }


  ngOnInit() {   

    this.dataApi = this.route.snapshot.data['dashboard'];


    if(this.dataApi.status_code==1)
    {                                  
        obtained = this.dataApi.data1.obtained                                                    

    }         

  }

dash: any ={       
    "series": [
        {
            "name": "progress",
            "className": "ct-grey",
            "value":  50-obtained
    },
      {
        "name": "done",
        "className": "ct-allow",
        "value":  obtained
      }


    ]       
}

DonutChart: Chart = {
    type: 'Pie',
    data: this.dash,
    options: {
        donut: true,
        startAngle: 0,   
        labelInterpolationFnc: function (value) {           
            return obtained;
        }    
    },
    events: {
        draw(data: any): void {
            if (data.type === 'label') {
                if (data.index === 0) {
                    data.element.attr({
                        dx: data.element.root().width() / 2,
                        dy: data.element.root().height() / 2
                    });
                } else {
                    data.element.remove();
                }
            }

        }
    }
};

}
3

There are 3 answers

0
codetinker On

I just got chartist work on angular 6. Im using js to fix this instead of ts.

Install these:

npm i chartist --save
npm i @types/chartist --save-dev

then add css and js in angular.json

"scripts": ["node_modules/chartist/dist/chartist.min.js"],
"styles": ["node_modules/chartist/dist/chartist.min.css"]

in app.component

declare let $: any;
import * as Chartist from 'chartist';

...

ngOnInit() {
    const me = this;

    setTimeout(() => {
      me.loadChart();
    }, 500);
}

loadChart() {
  $(function() {
    var chart = new Chartist.Pie('.ct-chart', {
      series: [10, 20, 50, 20, 5, 50, 15],
      labels: [1, 2, 3, 4, 5, 6, 7]
    }, {
      donut: true,
      showLabel: false
    });

    chart.on('draw', function(data) {
      if(data.type === 'slice') {
        // Get the total path length in order to use for dash array animation
        var pathLength = data.element._node.getTotalLength();

        // Set a dasharray that matches the path length as prerequisite to animate dashoffset
        data.element.attr({
          'stroke-dasharray': pathLength + 'px ' + pathLength + 'px'
        });

        // Create animation definition while also assigning an ID to the animation for later sync usage
        var animationDefinition = {
          'stroke-dashoffset': {
            id: 'anim' + data.index,
            dur: 1000,
            from: -pathLength + 'px',
            to:  '0px',
            easing: Chartist.Svg.Easing.easeOutQuint,
            // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible)
            fill: 'freeze'
          }
        };

        // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation
        if(data.index !== 0) {
          animationDefinition['stroke-dashoffset'].begin = 'anim' + (data.index - 1) + '.end';
        }

        // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us
        data.element.attr({
          'stroke-dashoffset': -pathLength + 'px'
        });

        // We can't use guided mode as the animations need to rely on setting begin manually
        // See http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-animate
        data.element.animate(animationDefinition, false);
      }
    });

    // For the sake of the example we update the chart every time it's created with a delay of 8 seconds


  });
}

in app.html

<div class="ct-chart ct-perfect-fourth"></div>

goto https://gionkunz.github.io/chartist-js/examples.html and copy paste any example chart there to your app. it should work without any problem =)

0
Arno 2501 On

I wanted to keep it encapsulated to a single component where I could bind data so I did like that:

npm install chartist --save
npm install @type/chartist --save-dev

Create a simple component

/* bar-char.component.ts' */
import {  AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Input, ViewChild, ViewEncapsulation } from '@angular/core';
import { Bar, IChartistBarChart, IChartistData } from 'chartist';

@Component({
  selector: 'bar-chart',
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None, // <-- Very important otherwise style imported from node_modules wont apply
  template: `<div #elt></div>`,
  styleUrls: [
    './bar-char.component.scss'
  ]
})
export class BarChartComponent implements AfterViewInit {
  @Input() public data: IChartistData;
  public chart: IChartistBarChart;

  @ViewChild('elt', { static: false })
  private elt: ElementRef;

  public ngAfterViewInit(): void {
    if (this.data) {
      this.chart = new Bar(this.elt.nativeElement, this.data);
    }
  }
}

Then in the scss of the component we import styles from chartist

/* bar-char.component.scss' */
@import '~chartist/dist/scss/chartist.scss'; /* <-- import styles from chartist node_modules */

We would use it like that:

/* app.component.ts */
@Component({
  selector: 'pms-root',
  template: `<bar-chart [data]="myChartData"></bar-chart>`
})
export class AppComponent {
  public myChartData: IChartistData = {
    labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      series: [
      [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
      [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
    ]
  };

/* Don't forget to declare it in your module */

@NgModule({
  declarations: [
    BarChartComponent, // ...

Tested on angular 8

0
Gotts On

I had the same issue and I got it working. It seems the watch is only on the outer data object. If you just change the underlying series and labels it doesn't trigger a redraw of the chart.

However if you replace the whole data object within your chart object then that will trigger a redraw. Works for me.

Also if you still have trouble you can always directly call the API as follows:

         var chartDom = document.getElementById("mychart");
         if(chartDom && chartDom["__chartist__"])
            chartDom["__chartist__"]["update"]();