Here, we will learn about creating dynamic AM-Charts in Angular 8. Charts are very useful for showing data and people understand the data very easily. So we will use am-charts for creating dynamic charts in Angular-8.

We will use the dummy API for it.

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

So, create a new project in Angular 8 using your favorite code editor.

After creating it, open the project and open app.component.html file and add the code in it.

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

Open the app.component.ts file and add the code in it.

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();
      }
    });
  }

}

Finally, add the reference for HttpClientModule in the app.module.ts file and that’s it.

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 { }

Output:

output