[Chartjs]-Can't pass array to chart.js which got its data from @Input

2πŸ‘

βœ…

I think this is an Angular lifecycle issue. Your problem is in how you are using the @Input data. You clearly want to take the data that is coming in with dataArrayInput, but you aren’t accessing it correctly.

Move your assignment of the variables that depend on the @Input values to within the ngOnInit method. The value of the @Input variables is not available during construction of the component, so when you create the dependent variables, you are initializing them with undefined.

export class BarChartComponent implements OnInit {

  public chartType = 'bar';

  @Input() chartLabelInput: string;
  @Input() dataArrayInput: number[];

  public chartLabel: string;
  public dataArray: number[];
  public chartDatasets: Array < any > ;

  @Input() labelArray: string[];
  public chartLabels: Array < any > ;

  @Input() chartOptionsInput: any;
  public chartOptions;

  constructor() {}
  public chartClicked(e: any): void {}
  public chartHovered(e: any): void {}

  ngOnInit(): void {
    this.dataArray = this.dataArrayInput;
    this.chartDatasets = [{
      data: this.dataArray,
      label: this.chartLabel
    }];
    this.chartLabels = this.labelArray;
    this.chartOptions = this.chartOptionsInput;
  }
}

Take a look at this question and this question.

Leave a comment