Chartjs-Charts.js convert negative data

0👍

Math.abs expects a single number input according to ts declarations. So you need to get the number from the array by specefying [0] behind it. After that you need to make it an array again since chart.js expects an array. So your code will look like this:

barLabel = ["13.03.2022"];
barData = [[645.54], [- 114.24]];

@Input() barData!: (number | ScatterDataPoint | BubbleDataPoint)[][];
@Input() barLabel!: string[];

public barChartType: ChartType = "bar";
public barChartData: ChartConfiguration["data"];
defaultBarChartData: Partial<ChartConfiguration['data']>;

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

  if (
    this.barData !== undefined &&
    this.barLabels !== undefined &&
    Array.isArray(this.barData) &&
    this.barData.length > 0 &&
    Array.isArray(this.barLabels) &&
    this.barLabels.length > 0 
  ) 
  {
    this.barChartData = {
      ...this.defaultBarChartData,
      ...{ labels: [" "] },
    } as ChartConfiguration['data'];
    this.barChartData.datasets[0].data = this.barData[0];
   } else {
    throw new Error('Charts must have their data and labels inputs defined.');
   }
  }

public barChartOptions: ChartConfiguration["options"] = {...}

Leave a comment