AmCharts In Angular

AmCharts In Angular

In this article, we will how to create dynamic AMCharts in angular application. Data may be displayed using charts, and people can simply understand the data. Therefore, in Angular, we will create dynamic charts using the amCharts.

Here, We will use the dummy API for data binding.

https://api.myjson.com/bins/zg8of

So, let's start with the implementation

First, we need to create a new angular application using the following command in the terminal.

ng new am-charts-angular

Now, we need to install amcharts npm packages using the following command in the terminal.

npm install @amcharts/amcharts4 --save

Now, add the HttpClientModule module in the app.module.ts file using the following code.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now, add the following code under the app.component.html file.

<div id="chartdiv" style="width: 100%; height: 500px">
</div>
<div id="l-0"></div>

Now, add the following code under the app.component.ts file.

import { Component, NgZone } from "@angular/core";
import * as am4core from "@amcharts/amcharts4/core";
import * as am4charts from "@amcharts/amcharts4/charts";
import am4themes_animated from "@amcharts/amcharts4/themes/animated";
import { HttpClient } from '@angular/common/http';

am4core.useTheme(am4themes_animated);

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  private chart: am4charts.XYChart;
  tempData: any;
  dates = [];
  newData = [];
  gr = [];
  data = [];
  constructor(private _zone: NgZone, private _http: HttpClient) { this.getApiData(); }

  getApiData() {
    this._http.get("https://api.myjson.com/bins/zg8of").subscribe(res => {
      this.tempData = res;
      this.tempData.forEach(values => {
        this.data.push(values);
      });
      console.log(this.data);
      this._zone.runOutsideAngular(() => {
        var result = this.groupBy(this.data, function (item) {
          return ([item.Name]);
        });

        result.forEach(b => {
          var d1 = b.map(function (i) {
            return i.Month;
          });
          Object.assign(this.dates, d1);
        });

        this.dates.forEach(b => {
          var item = { sales_figure: b };
          var i = 0;
          result.forEach(c => {
            var el = c.filter(function (e) {
              return e.Month == b;
            });
            if (el && el.length > 0) {
              item[c[i].Name.toUpperCase()] = el[0].Sales_Figure;
              if (this.gr.filter(function (g) {
                return g == c[i].Name.toUpperCase();
              }).length <= 0) {
                this.gr.push(c[i].Name.toUpperCase());
              }
            }
            i++;
          });

          if (Object.keys(item).length > 1)
            this.newData.push(item);
        });
        let chart = am4core.create("chartdiv", am4charts.XYChart);
        am4core.options.minPolylineStep = Math.ceil(this.newData.length / 50);
        am4core.options.commercialLicense = true;
        chart.paddingRight = 20;
        chart.data = this.newData;

        var categoryAxis = chart.xAxes.push(new am4charts.CategoryAxis());
        categoryAxis.dataFields.category = "sales_figure";
        categoryAxis.renderer.minGridDistance = 70;
        categoryAxis.fontSize = 12;

        var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
        valueAxis.fontSize = 12;
        valueAxis.title.text = "Sales Figure";

        chart.legend = new am4charts.Legend();
        chart.legend.position = "top";
        chart.legend.fontSize = 12;

        var markerTemplate = chart.legend.markers.template;
        markerTemplate.width = 10;
        markerTemplate.height = 10;

        var legendContainer = am4core.create("l-0", am4core.Container);
        legendContainer.width = am4core.percent(100);
        chart.legend.parent = legendContainer;

        var legendDiv = document.getElementById("l-0");
        function resizeLegendDiv() {
          legendDiv.style.height = chart.legend.measuredHeight + "px";
          legendDiv.style.overflow = "hidden";
        }

        chart.legend.events.on('inited', resizeLegendDiv);
        chart.colors.list = [am4core.color("#0D8ECF"), am4core.color("#FF6600"), am4core.color("#FCD202"), am4core.color("#B0DE09"), am4core.color("#2A0CD0"), am4core.color("#CD0D74"), am4core.color("#CC0000"), am4core.color("#00CC00"), am4core.color('#ffd8b1'), am4core.color("#990000"), am4core.color('#4363d8'), am4core.color('#e6194b'), am4core.color('#3cb44b'), am4core.color('#ffe119'), am4core.color('#f58231'), am4core.color('#911eb4'), am4core.color('#46f0f0'), am4core.color('#f032e6'), am4core.color('#bcf60c'), am4core.color('#fabebe'), am4core.color('#008080'), am4core.color('#e6beff'), am4core.color('#9a6324'), am4core.color('#fffac8'), am4core.color('#800000'), am4core.color('#aaffc3'), am4core.color('#808000'), am4core.color('#ffd8b1'), am4core.color('#000075')];
        this.gr.forEach(d => {

          var series = chart.series.push(new am4charts.LineSeries());
          series.dataFields.valueY = d;
          series.name = d;
          series.dataFields.categoryX = "sales_figure";
          series.tooltipText = "{name}: [bold]{valueY}[/]";
          series.strokeWidth = 2;
          series.minBulletDistance = 30;
          series.tensionX = 0.7;
          series.legendSettings.labelText = "[bold]" + "{name}";

          var bullet = series.bullets.push(new am4charts.CircleBullet());
          bullet.circle.strokeWidth = 2;
          bullet.circle.radius = 3;
          bullet.circle.fill = am4core.color("#fff");

          var bullethover = bullet.states.create("hover");
          bullethover.properties.scale = 1.2;
          chart.cursor = new am4charts.XYCursor();
          chart.cursor.behavior = "panXY";
          chart.cursor.snapToSeries = series;
        });

        chart.scrollbarX = new am4core.Scrollbar();
        chart.scrollbarX.parent = chart.bottomAxesContainer;

        this.chart = chart;
      });
    });
  }

  groupBy(array, f) {
    var groups = {};
    array.forEach(function (o) {
      var group = JSON.stringify(f(o));
      groups[group] = groups[group] || [];
      groups[group].push(o);
    });
    return Object.keys(groups).map(function (group) {
      return groups[group];
    })
  }

  ngOnDestroy() {
    this._zone.runOutsideAngular(() => {
      if (this.chart) {
        this.chart.dispose();
      }
    });
  }

}

Now, run the application using the ng serve command into the terminal and see the browser screen, now we are able to read API data and generate chart as per API data response. 

AmCharts In Angular

Conclusion

In this article, we learned how to create dynamic AMCharts in angular application.

I hope this article helps you and you will like it.👍

Please give your valuable feedback and comments or suggestion in the comment section

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post