[Chartjs]-Angular 5 and chart.js ts error

2👍

Try angular2-chartjs which is very useful angular library for chartjs

npm install angular2-chartjs chart.js --save
npm install @types/chart.js --save

Import and declare ChartModule in app.module.ts

...
import { ChartModule } from 'angular2-chartjs';

@NgModule({
  imports:      [...,  ChartModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})

In AppComponent.ts declare chart chart, type, data, options properties and assign values in ngOnInit method

...
@ViewChild(ChartComponent) chart: ChartComponent;
type;
data;
options;
...

ngOnInit() {

    this.type = 'horizontalBar';
    this.data = {
        labels: ["5 star", "4 start", "3 start", "2 star", "1 star"],
        datasets: [
            {
                fill: true,
                label: false,
                backgroundColor: ["#a1a7b3", "#a1a7b3", "#a1a7b3", "#a1a7b3", "#a1a7b3"],
                data: [10, 2, 5, 4, 5]
            }
        ]
    }
    this.options = {
        maintainAspectRatio: false,
        responsive: false,
        legend: { display: false },
        title: {
            display: false,
            text: ''
        },
        scales:
            {
                yAxes: [{
                    // barPercentage: 0.4,
                    barThickness: 20,
                    barPercentage: .5,
                    categoryPercentage: .2,
                    isFixedWidth: true,
                    //Number - Pixel width of the bar
                    barWidth: 20,
                    gridLines: {
                        display: false
                    },
                    ticks: {
                        min: 0,
                        stepSize: 1,
                        fixedStepSize: 1,
                    }
                }],
                xAxes: [{
                    display: false,
                    gridLines: {
                        display: false
                    },
                    ticks: {
                        min: 0,
                        stepSize: 1,
                        fixedStepSize: 1,
                    }
                }],
            }
    }
}

In AppComponent.html template include chart tag

...
<chart #chart [type]="type" [data]="data" [options]="options" style="height: 100%"></chart>

Preview link for implementation of your horizontal bar https://stackblitz.com/edit/angular-geq984

Leave a comment