How to implement chart.js in Angular2

后端 未结 6 1669
刺人心
刺人心 2020-12-14 09:19

I\'m using Angular2-rc4 with angular-cli webpack and would like to implement a chart.js library.

I\'ve installed chart.js to my project using:

6条回答
  •  不知归路
    2020-12-14 10:12

    I had a similar issue, it turned out I was referencing an old example.

    First, as you've already correctly done, install the library using NPM:

    npm install chart.js --save
    

    Then, in your component, import the library:

    import Chart from 'chart.js';
    

    To get up and running with a quick example, have a look at the example code in the Chart.js documentation or see my example below.


    dashboard.component.ts

    import Chart from 'chart.js';
    import { ViewChild, Component, ElementRef, OnInit } from '@angular/core';
    
    @Component({
        selector: 'app-dashboard',
        template: ''
    })
    
    export class DashboardComponent implements OnInit {
        @ViewChild('donut') donut: ElementRef;
    
        constructor(
        ) { }
    
        ngOnInit() {
            let donutCtx = this.donut.nativeElement.getContext('2d');
    
            var data = {
                labels: [
                    "Value A",
                    "Value B"
                ],
                datasets: [
                    {
                        "data": [101342, 55342],   // Example data
                        "backgroundColor": [
                            "#1fc8f8",
                            "#76a346"
                        ]
                    }]
            };
    
            var chart = new Chart(
                donutCtx,
                {
                    "type": 'doughnut',
                    "data": data,
                    "options": {
                        "cutoutPercentage": 50,
                        "animation": {
                            "animateScale": true,
                            "animateRotate": false
                        }
                    }
                }
            );
        }
    }
    

提交回复
热议问题