ngx-charts - Horizontal Bar Charts dynamically adjust bar thickness when data is updated

Using Angular and ngx-charts to display data fetched from the server works perfectly on initial load trigger with the ngOnInit() method calling getStats() function. Everything loads as expected: https://i.sstatic.net/8OsbD.png


However, upon clicking the Get Data button and re-sending the same request to the server (getStats()), the table gets re-rendered with the bar lines appearing thin: https://i.sstatic.net/VJ2qT.png

The thinning out of bar lines is observed.


Html:

<div class="row shadow">
    <div class="col" style="height: 80vh; width: 100%;"> 
        <ngx-charts-bar-horizontal
            [scheme]="colorScheme"
            [results]="data"
            [gradient]="gradient"
            [xAxis]="showXAxis"
            [yAxis]="showYAxis"
            [legend]="showLegend"
            [showXAxisLabel]="showXAxisLabel"
            [showYAxisLabel]="showYAxisLabel"
            [xAxisLabel]="xAxisLabel"
            [yAxisLabel]="yAxisLabel"
            (select)="onSelect($event)">
        </ngx-charts-bar-horizontal>                                
    </div>
</div>


Ts Code:

    export class StatsComponent implements OnInit {

  constructor(
    private adminService: AdminService,
    private toastr: ToastrService,
    private datePipe: DatePipe,
    private formBulder: FormBuilder,
    private changeDetection: ChangeDetectorRef ) { }

    days = 7; // Days you want to subtract
    date = new Date();
    endMonth = this.date.getUTCMonth() + 1; //months from 1-12
    endDay = this.date.getUTCDate();
    endyear = this.date.getUTCFullYear();
    endDate = this.endyear + '/' + this.endMonth + '/' + this.endDay;
    last = new Date(this.date.getTime() - (this.days * 24 * 60 * 60 * 1000));
    startDay = this.last.getDate();
    startMonth= this.last.getMonth()+1;
    startYear = this.last.getFullYear();
    startDate = this.startYear + '/' + this.startMonth + '/' + this.startDay;

  statsSearchFrom = this.formBulder.group({
    startTime: [this.startDate, Validators.required],
    endTime: [this.endDate, Validators.required]
  });

  agents: User[];
  data: any[] = [];
  multi: any[];
  // view: any[] = [100%, 800];
  // bar chart options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Number of Tickets';
  showYAxisLabel = true;
  yAxisLabel = 'Agent';

  colorScheme = {
    domain: ['#263859', '#a7d129', '#21e6c1', '#278ea5', '#7045af', '#e14594', '#ed6363', '#3c6562']
  };

  ngOnInit() {
    this.getAllAgents();
  }

  getStats() {
    const startTime = this.datePipe.transform(this.statsSearchFrom.controls['startTime'].value, 'ddMMyyyy');
    const endTime = this.datePipe.transform(this.statsSearchFrom.controls['endTime'].value, 'ddMMyyyy');
    this.adminService.getAgentStats(this.agents, startTime, endTime).subscribe(response => {
      this.agents = response;
      for (const agent of this.agents) {
        const point: any = {'name': agent.username, 'value': agent.nbOfClosedEmails};
        this.data.push(point);
      }
      this.data = [...this.data];
    }, error => {
      this.toastr.error('Error while getting the statistics.')
    });
  }

  getAllAgents() {
    this.adminService.getAllAgents().subscribe(response => {
      this.agents = response;
      this.agents = [...this.agents];
      this.getStats();
    }, error => {
      this.toastr.error('Error while getting the agents.');
      console.error(error);
    });
  }

Answer №1

The issue stemmed from the ngx-charts barPadding setting. By adjusting it to a specific value, the bars consistently maintained their thickness across all requests.

To resolve this issue, include the following code snippet: [barPadding]="1" within the

<ngx-charts-bar-horizontal>
HTML element.

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

What sets apart a private static function from a public static function in TypeScript?

Exploring the nuances of angular2 services: what distinguishes a private static function from a public static function in typescript? public static getUserStockList(): Stock[] { /* TODO: implement http call */ return WATCHLIST; } vs. priv ...

Strategies for redirecting search queries when adding a new path

Issue I am facing a challenge with pushing a new path to the URI while maintaining existing search queries. For example: Current URL: https://example.com/foo?bar=123&foobar=123 When I use history.push('newPath'), I end up with https://exa ...

Navigating json information in Angular 6: Tips and Tricks

I'm currently working on an Angular 6 project and I've encountered an issue with iterating over JSON data fetched using httpClient. If anyone has a solution, I would greatly appreciate the help. The JSON data structure is as follows: Json data ...

How can I create an interceptor in Angular2 to detect 500 and 404 errors in my app.ts file?

Creating an Angular2 Interceptor for Handling 500 and 404 Errors in app.ts In my app.ts file, I am looking to implement an interceptor that can detect a 500 or 404 error so that I can appropriately redirect to my HTML 404 or HTML 500 pages. Is this funct ...

Unlocking the potential for over 1000 search results using the GitHub API

Is there a way to display more than 1000 search results when listing the most starred Github repositories created in the last 30 days? I keep getting an error message that says: { "message": "Only the first 1000 search results are available", "documen ...

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...

What kind of type is recommended to use when working with async dispatch in coding?

For my TypeScript and React project, I am currently working on an action file called loginAction.tsx. In this file, there is a specific line of code that handles the login functionality: export const login = (obj) => async dispatch => { dispatch( ...

Implementing Lazy Loading in Angular 7 with deeper nested children components

I might have some difficulty explaining the issue, but I have a StackBlitz example to demonstrate. Check out this StackBlitz example Take note of the Lazyloading 'users'... app.routes.ts //import { NgModule } from '@angular/core'; i ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

Encountering a TypeError in Angular2 and Ionic2: 'Pst.Base64.decode' is not defined when evaluating the object

After upgrading to Ionic2 RC0 from Beta11, which uses ng2 final, I encountered an error while building for ios. The error message states: "EXCEPTION: undefined is not an object (evaluating 'Pst.Base64.decode')." 0 949421 error EXCEPTION ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Steps to easily set up a date-range-filter in Angular 6!

I have put together a small StackBlitz project to showcase my current situation. My aim is to log all objects that fall within a specified date range. However, when I attempt to filter my objects, I am faced with an empty array as the result. I would like ...

Leverage Redux in Angular for account balance management

As I work on creating an app in Angular where users can make purchases and have the price deducted from their account balance, I've been delving into Redux. The scenario involves individual user accounts with independent balances and no interaction be ...

Using TypeScript with Vue allows you to customize the default export of Vue

Currently experimenting with Vue and TypeScript, attempting to compile to AMD in my tsconfig file. The type definition in vue/types/index.d.ts for Vue.js includes: export default Vue; However, this results in TypeScript compiling it like this: import V ...

Issue encountered with Next.js 13.4 and NextAuth: A Type Error stating that 'AuthOptions' is not compatible with type 'never'

Currently, I am in the process of developing a Next.js 13.4 project and attempting to configure NextAuth using the app/router. Unfortunately, I have encountered a type error that I am struggling to troubleshoot. Below is my route.ts file: import NextAuth, ...

typescript extending a type from a higher-level interface

Consider the TypeScript interface provided below: export interface Update { type: 'STATUS_UPDATE'; } I am interested in extending this interface by adding one more value to the type property, as shown here: export interface HttpUpdate extends ...

Encountering a non-constructor error while trying to import packages in React Typescript

I am currently working on a project that utilizes React with Typescript. While attempting to import a package, I encountered an error stating that the package lacks a constructor when I run the file. This issue seems to be prevalent in various packages, a ...

Troubleshooting: ngModel in Angular 2 Component does not properly update the parent model

I have been attempting to develop a wrapper component for input elements like checkboxes, but I am facing an issue where the parent variable (inputValue) is not updating even though it has been defined as an ngModel. The code snippet for my component look ...

The nest build process encounters errors related to TypeScript in the @nestjs/config package, causing it

Encountering several issues related to @nestjs/config, causing the npm build command to fail. However, npm run start:dev is still functional despite displaying errors. See below for screenshots of the errors and environment: https://i.sstatic.net/Wxkkn.png ...

Guide on changing the color of the selected item in mat-nav-list within angular 6

Recently diving into Angular 6 and facing an issue with my mat-toolbar integrated with mat-sidenav. Everything seems to be functioning fine, but I'm looking to customize the color for the active item in the side nav menu. Currently, all items have a ...