Angular data visualisation using chart.js

0👍

Example : https://stackblitz.com/edit/angular-ivy-psxufv

Using documentation of

https://valor-software.com/ng2-charts/#/GeneralInfo

Step 1 : npm install --save ng2-charts

Step 2 : npm install --save chart.js

app.module.ts

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

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

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

data.service.ts – Change to use your URL

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { InnerModel } from './model';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  // url = 'https://pastebin.com/raw/fvJkWEk5';
  url = 'http://localhost:4200/assets/data.json';

  constructor(private http: HttpClient) { }

  getChartData(): Observable<any> {
    return this.http.get(this.url);
  }
}

model.ts

export interface InnerModel {
  district_name: string;
  registration_time: string;
  sex: string;
  ctc_number: string;
}

export interface DataModel {
  id: string;
  data: InnerModel;
}

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from './data.service';
import { DataModel } from './model';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';

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

  public barChartOptions: ChartOptions = {
    responsive: true,
    scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
      }
    }
  };

  public barChartType: ChartType = 'bar';
  public barChartLegend = true;

  private dataSubsctiption: Subscription;

  public chartData: ChartDataSets[] = [
    { data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], label: 'Male' },
    { data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], label: 'Female' }
  ];

  months: Label[] = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'];


  constructor(private dts: DataService) {
  }

  ngOnInit(): void {
    this.dataSubsctiption = this.dts.getChartData().subscribe(
      (jsonData: DataModel[]) => {
        const newData =  [
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        ];
        jsonData.map((u, i) => {
          const index = u.data.sex.toLowerCase() === 'male' ? 0 : 1;
          const dataSetItem = newData[index];
          // tslint:disable-next-line:radix
          dataSetItem[parseInt(u.data.registration_time.split('-')[1]) - 1]++;
        });

        this.chartData[0].data =  newData[0];
        this.chartData[1].data =  newData[1];
      },
      err => {
        console.error(err);
      });
  }

  ngOnDestroy(): void {
    this.dataSubsctiption.unsubscribe();
  }
}

app.component.html

<div>
  <div>
    <div style="display: block">
      <canvas baseChart
        [datasets]="chartData"
        [labels]="months"
        [options]="barChartOptions"
        [legend]="barChartLegend"
        [chartType]="barChartType">
      </canvas>
    </div>
  </div>
</div>

Leave a comment