Utilize Charts.js to transform negative values into graphical representations

I am struggling with transforming the expense data into a positive number in my bar chart. The data consists of both income and expenses, and I want to display them as positive numbers for easier comparison. I attempted using Math.abs(this.barData[1]) in ngOnInit, but encountered the error: Argument of type '(number | ScatterDataPoint | BubbleDataPoint)[]' is not assignable to parameter of type 'number'.

Any help would be greatly appreciated!

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: this.barData[0],
        label: "Income",
        backgroundColor: "#3ABD32",
      },
      {
        data: this.barData[1],
        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"] = {...}

Answer №1

When using Math.abs in TypeScript declarations, remember that it requires a single number input. To achieve this, extract the number from the array by specifying [0] after it. Then, convert it back to an array since chart.js expects an array input. Your code should be structured 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"] = {...}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular, dynamically updating ApexCharts series daily for real-time data visualization

I am currently working with apexchart and struggling to figure out how to properly utilize the updateseries feature. I have attempted to directly input the values but facing difficulties. HTML <apx-chart [chart]="{ type: ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

Creating a function that can have either one or two arguments, with the types of the arguments determined by a specific string literal

I am looking to create a function called emitEvent(event, extra?), which will be restricted by a string literal enum of known strings such as POPUP_OPEN and POPUP_CLOSED. The function will accept a second argument that is a specifically defined dictionary ...

Exploring Angular 4's Capabilities: Navigating a Multi-Dimensional Array

I am currently working with a multi-dimensional array that has two keys, and it is structured as follows: user: any = {}; // The index is incremented within a for loop to add values to the user object (this part is functioning correctly) this.user[index++ ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

Typescript tutorial: Implementing a 'lambda function call' for external method

The Issue Just recently diving into Typescript, I discovered that lambda functions are utilized to adjust the value of this. However, I find myself stuck on how to pass my view model's this into a function that calls another method that hasn't b ...

Obtaining the identifier of a generic type parameter in Typescript

Is there a method in TypeScript to retrieve the name of a generic type parameter? Consider the following method: getName<T>(): string { .... implement using some operator or technique } You can use it like this: class MyClass{ } getName< ...

Leveraging multiple routes for a single component in Angular 6

Creating a component named Dashboard for admin requires passing the username in the route to find user information. This is the routing setup: {path:'dashboard/:username',component:DashboardComponent,children:[ {path:'role',component: ...

Next.js Error: Inconsistent text content between server-rendered HTML and hydration. Unicode characters U+202F versus U+0020

Having issues with dates in Next.js development. Encountering three errors that need to be addressed: Warning: Text content did not match. Server: "Tuesday, January 24, 2023 at 11:01 AM" Client: "Tuesday, January 24, 2023 at 11:01 AM" ...

Exploring the Node environment setup within Nest.js

Currently, I am in the midst of setting up a Nest.js project and seeking an efficient solution for defining the Node environment used by the ConfigService to load environment variables: import { Module } from '@nestjs/common'; import { ConfigSer ...

Aurelia validation is failing to work properly when the form is already populated with data

Struggling to implement validation on an edit model-view that is data-bound in the activate method of its view-model. The create.ts file works smoothly with similar code, but without the need to load data. Surprisingly, the validation functions correctly ...

Playwright failing to execute GraphQL tests due to TypeScript configuration problems

I'm facing an issue with my repo where I am running tests using Playwright against a graphQL URL. Despite configuring the tests, there is an error indicating that the environment variable defining the environment cannot be found. The repository in qu ...

Validation is a must in Angular 2

I am facing an issue with the default required validator in angular forms. My form has one input field and a submit button. There are two important files: example.form.ts example.form.template.html Here is my code setup: In the .ts file, I create ...

The issue I'm facing with Angular 8 is that while the this.router.navigate() method successfully changes the URL

As someone who is relatively new to Angular, I am currently in the process of setting up the front end of a project using Angular 8. The ultimate goal is to utilize REST API's to display data. At this point, I have developed 2 custom components. Logi ...

Error TS2346: The parameters provided do not match the signature for the d3Service/d3-ng2-service TypeScript function

I am working with an SVG file that includes both rectangular elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x ...

Tips for resolving the 'JSX is not defined no-undef' error post TypeScript 4.4.2 update

Upon upgrading to TypeScript 4.4.2 from TypeScript 3.8.2, I have encountered numerous errors such as error 'x' is not defined no-undef. For instance, one of the errors is error 'JSX' is not defined no-undef. Upon closer inspection, most ...

Extract from Document File

After receiving a PDF through an Angular Http request from an external API with Content Type: application/pdf, I need to convert it into a Blob object. However, the conventional methods like let blobFile = new Blob(result) or let blobFile = new Blob([resul ...

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...