How to implement Chart.js in Angular 2?

I am using the latest version of Angular 2, V4.0.0, and I want to use the graphs from the Chart.js library in my project without many complications.

How can I implement Chart.js in my Angular project, which does not give me problems in the final version?

+4
source share
4 answers

You can implement Chart.js in a simple way with the following instructions:

1. Create a new project with angular-cli, skip if you already have one created

ng new example-chartjs

2. Install Chart.js in your project

npm install chart.js --save

3. Import a chart into its component

import Chart from 'chart.js';

4. Using a chart in your view and component

In your opinion:

<canvas id="myChart" width="400" height="400"></canvas>

:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

:

import { Component, OnInit } from '@angular/core';
import Chart from 'chart.js';

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}

".angular-cli.json"

1.

"styles": [
  "styles.css"
],
"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/chart.js/dist/Chart.min.js"
]

2. "any"

declare var Chart:any;

3.

:

<canvas id="myChart" width="400" height="400"></canvas>

:

ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {...});

}

:

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

declare var Chart:any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html'
})

export class DashboardComponent implements OnInit {

  constructor() { }

  ngOnInit() {

    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {....});

  }

}
+15


npm install chart.js --save


npm install @types/chart.js --save

-
import * as Chart from 'chart.js';

+7

Chart.js Angular ( npm install chart.js --save):

src/
  assets/
  app/
    charjs/
    services/

report.service.ts:

///report.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ReportService {
  constructor(public http: Http) {
  }
  getReports() {
    return this.http.get('assets/adverseimpact.json')
      .map(res => res.json());
  }
}

, Angular tutorial, , ( ) Json .

( )

: app.module.ts :

//app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpModule, JsonpModule } from '@angular/http';
import { ReportService } from './services/report.service';
import { ChartjsComponent } from './chartjs/chartjs.component';

@NgModule({
  declarations: [
    AppComponent,
    ChartjsComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [ReportService],
  bootstrap: [AppComponent]
})
export class AppModule { }

chartjs.component.js AfterViewInit OnInit. , , - , .

//chartjs/chartjs.component.ts

import { Component, AfterViewInit,ViewChild, ElementRef } from '@angular/core';
import Chart from 'chart.js';
import { Respon2se } from '@angular/http';
import 'rxjs/add/operator/map';
import { ReportService } from '../services/report.service';


@Component({
  selector: 'app-chartjs',
  templateUrl: './chartjs.component.html',
  styleUrls: ['./chartjs.component.css']
})
export class ChartjsComponent implements AfterViewInit {

  @ViewChild('graphcanvas') mycanvas:ElementRef;
  createData;
  chartOptions;

  constructor(public reportService: ReportService) {

  }

  ngAfterViewInit() {

    this.reportService.getReports().subscribe(reportsData => {
      this.createData = {
        labels: 'Scatter Dataset',
        datasets: [{
          label: "advImpact",
          data: reportsData,

        }]
      };

      this.chartOptions = {
        legend: {
          display: false,
          position: 'top',
          labels: {
            boxWidth: 80,
            fontColor: 'black'
          }
        },
        scales: {
          xAxes: [{
            gridLines: {
              display: false,
              color: "black"
            },
            scaleLabel: {
              display: true,
              labelString: "Job Role Size",
              fontColor: "red"
            }

          }],
          yAxes: [{
            gridLines: {
              color: "black",
              display: false
            },
            scaleLabel: {
              display: true,
              labelString: "Adverse Impact",
              fontColor: "green"
            }
          }]
        },
        layout: {
          padding: {
            left: 0,
            right: 50,
            top: 50,
            bottom: 0
          }
        },
        maintainAspectRatio: false
      };

      let ctx = this.mycanvas.nativeElement.getContext('2d');

      new Chart(ctx, {
        type: 'bubble',
        data: this.createData,
        options: this.chartOptions,
        responsive: false
      });

    });
  }

}

;

. , charjs new Chart , ChartOptions - , . , , .

, , html:

//chartjs/chartjs.component.html

<div style="height: 600px;width: 600px">
  <canvas #graphcanvas></canvas>
</div>

I hope this helps someone who cannot implement other methods.

+4
source

I believe that in Angular, charts will work as shown below because the context is accessible afterViewInit () is not onInit ()

  import { Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
    import Chart from 'chart.js';

    @Component({
        selector: 'app-statistics',
        templateUrl: './statistics.component.html',
        styleUrls: ['./statistics.component.css']
    })
    export class StatisticsComponent implements AfterViewInit{
        @ViewChild('myChart') Chart: ElementRef;
        constructor() { 

        }

        ngAfterViewInit() {
            var ctx = this.Chart.nativeElement.getContext('2d')
            var myChart = new Chart(ctx,{...})
        }
    }
0
source

Source: https://habr.com/ru/post/1673753/


All Articles