9
votes

I'm starting new Angular application which I initialised with Angular-CLI (beta 22.1). But when I add test-data (5 values) to my chart it seems to scale wrong and only shows the first two values and streched them over the whole length of the graph (see picture).

enter image description here

The project is otherwise blank and does not contain any CSS whatsoever.

My app.component.html:

<div>
    <canvas baseChart [datasets]="_numbers" [labels]="_labels" [options]="_chartOpt" [colors]="_chartColours" [legend]="_chartLegend" [chartType]="_chartType" width="600px">
    </canvas>
<div>

The app.component.ts

import { Component } from '@angular/core';
import { BaseChartDirective } from "ng2-charts/ng2-charts";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private _numbers: any[] = [
      {
        label: "Test",
        data: [10,2,6,7] // should cause 4 points in the chart
     }
  ];

  private _chartOpt: any = {
        responsive: true
  };

  public _chartColours:any[] = [];

  private _labels: string[] = [];
  private _chartLegend: boolean = false;
  private _chartType: string = "line";
}

The chart.js library is added via the angular-cli.json:

"scripts": [
         "../node_modules/chart.js/dist/Chart.bundle.min.js"
      ],

I really don't know where I'm going wrong. I've tried many different options (responsive: true/false, maintainAspectRatio : true/false, wrapping the <canvas> in <div> and without, CSS Styles, width/height attributes, ...) but can't seem to get this one to work. I even downgraded the ng2-charts version to one that I reviously worked with, but with no luck.

Let me know if you need anymore code.

2
Have you tried assigning labels? Like real values, not empty string array? Maybe a silly question, I haven't used this charts myself, but still, the documentation says: "It's necessary for charts: line, bar and radar"Ilya Luzyanin
@IlyaLuzyanin Thanks for the hint. That was actually it... Be my guest to write it up as an answer and I'll accept it.Daniel Lerps
Glad it helped! Posted as an answerIlya Luzyanin

2 Answers

9
votes

labels property must be defined along with values. According to documentation for properties:

labels (?Array) - x axis labels. It's necessary for charts: line, bar and radar.

So specifying actual values for labels will do the trick.

1
votes

You need to put a condition inside the canvas, e.g., show it when the data is loaded or your array.length > 0

Example:

<canvas baseChart *ngIf="showMyChart" [datasets]="_numbers"
     [chartType]="_chartType" width="600px">
</canvas>