[Chartjs]-Chart.js bar chart with nested array

2👍

Move the initializing value to defaultBarChartData logic to ngOnInit method.

From Angular – Input,

Decorator that marks a class field as an input property and supplies configuration metadata. The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property’s value.

To guarantee the variables with @Input() decorator are updated with value, thus the ngOnInit is needed.

ngOnInit()

Initialize the directive or component after Angular first displays the data-bound properties and sets the directive or component’s input properties.

defaultBarChartData: Partial<ChartConfiguration['data']>;

ngOnInit(): void {
  this.defaultBarChartData = {
    labels: this.barLabels,
    datasets: [
      {
        data: this.barData[0],
        label: 'Income',
        backgroundColor: '#3ABD32',
      },
      {
        data: this.barData[1],
        label: 'Expense',
        backgroundColor: '#E02A45',
      },
    ],
  };

  ...
}

Sample StackBlitz Demo

Leave a comment