Selecting any of the bar chart labels will reveal just a two-day timeframe

My bar chart is behaving strangely - when I click on all labels, it only shows two days instead of updating as expected. I suspect it may be due to a bad implementation involving parsing. Can anyone provide assistance?

I have created a minimum example on Stackblitz: https://stackblitz.com/edit/angular-13-lsvqov?file=src%2Fapp%2Fapp.component.ts

    this.chart = new Chart('eventsChart', {
        type: 'bar',
        data: {
          datasets: this.generateChartData(mergedKeys)
        },
        options: {
          plugins: {
            tooltip: {
              callbacks: {
                title: context => {
                  const d = new Date(context[0].parsed.x);
                  return d.toLocaleString([], {
                    day: '2-digit',
                    month: 'short',
                    year: 'numeric'
                  });
                }
              }
            }
          },
          scales: {
            x: {
              type: 'time',
              time: {
                unit: 'day'
              }
            },
            y: {
              ticks: {
                stepSize: 1
              }
            }
          },
          aspectRatio: 2,
          maintainAspectRatio: false,
          responsive: true
        }
      });

  private generateChartData(keys: string[]) {
    return keys.map((key: string) => {
      return {
        label: key,
        data: this.dataSource,
        parsing: {
          xAxisKey: 'periodStartTime',
          yAxisKey: `keyStats.${key}`
        },
        backgroundColor: labelColor[key]
      };
    });
  }

Answer №1

To set up the Min Max Configuration for the time cartesian axis, you can display the minimum and maximum dates on your x-axis even if none of the labels are selected.

let sortedDates = data.map(x => x.periodStartTime).sort();

let minDate = sortedDates[0];
let maxDate = sortedDates[sortedDates.length - 1];

const mergedKeys = this.getChartKeys(data);

const chartGenericDataSets = this.generateChartData(mergedKeys);

this.chart = new Chart('eventsChart', {
  ...,
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
        },
        min: minDate,
        max: maxDate
      },
    },
    aspectRatio: 2,
    maintainAspectRatio: false,
    responsive: true,
  },
});

Check out the live demo on StackBlitz

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 is the correct way to activate buttons within a v-for loop in Vue.js?

My current situation is as follows: https://plnkr.co/edit/LdbVJCuy3oojfyOa2MS7 https://i.sstatic.net/ivWnE.png I am looking to activate the "Press me" buttons when the input changes. At this point, I have a code snippet that can detect when the input h ...

In angular.js, repeating elements must be unique and duplicates are not permitted

My view controller includes this code snippet for fetching data from an API server: $scope.recent_news_posts = localStorageService.get('recent_news_posts') || []; $http({method: 'GET', url: 'http://myapi.com/posts'} ...

Steps for downloading Excel or Zip files in Angular 4

Currently, my front end is built using Angular 4 and the back end is developed with Lumen 5.4. The task at hand requires me to export certain data as both an Excel and a zip file. I am utilizing the { saveAs } import from the package 'file-saver/Fil ...

Issue with Submit Event in React - Enter Key Fails to Trigger

I'm currently experimenting with a small front-end react project that's using Soundcloud's API. The project is quite basic at the moment - it takes user input and queries the API for related songs. I've encountered an issue where the en ...

Displaying each character of text individually with jQuery

I am trying to display the text within a ul tag one by one when hovering over some text. However, I am encountering an error. How can I resolve this issue? You can view the code for mouseover functionality by hovering over the "hover here hover again" lin ...

incongruity discovered during string conversion in HmacSHA256 within Ionic framework

I am facing an issue while trying to create a token in IONIC using the CryptoJS library. The signature generated by the method is different from what I expect. The expected signature is lLJuDJVb4DThZq/yP4fgYOk/14d3piOvlSuWEI/E7po= but the method provides m ...

What is causing checkboxes to malfunction within a form?

In my project, I have an array of objects representing pets: pets = [{key: 'dog', isChecked: true}, {key: 'hamster', isChecked: false}, {key: 'cat', isChecked: false}]; I want to display these objects as checkboxes. Here is ...

Let's set up a new project using Create React App and Node Sass with Chokidar, following the 7-1

Seeking a solution: I am relatively new to using React and would like to incorporate SASS into my project without ejecting or configuring webpack. My goal is to have isolated stylesheets for components, as well as global stylesheets for layout purposes. It ...

fill the designated column in accordance with the specific criteria

Is there a method to automatically fill in a specific column based on certain conditions? I am looking to populate the column labeled [Last] when the column index is 1 and the corresponding name is [First]. import {Component, OnInit} from '@angular ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

The element you are trying to interact with is currently not visible, therefore it cannot be accessed

Currently, I am working on a small Test Automation project using C# with Selenium WebDriver. I have run into an issue where some WebElements are not visible or have their 'Displayed' property set to 'false'. This prevents me from perfor ...

Is it possible to implement a redirect in Angular's Resolve Navigation Guard when an error is encountered from a resolved promise?

I have integrated Angularfire into my Angular project and am utilizing the authentication feature. Everything is functioning properly, however, my Resolve Navigation Guard is preventing the activation of the component in case of an error during the resolve ...

What steps are involved in launching an outdated Angular project?

Tasked with reviving an old Angular client in my company, I found myself grappling with outdated files and missing configurations. The lack of package.json, package-lock.json, and angular.json added to the confusion, while the presence of node modules in t ...

Efficient code for varying layouts of disabled Angular Material buttons

I've been wondering if there's a simpler way to customize the appearance of a disabled button using Angular Material. Currently, I achieve this by utilizing an ng-container and ng-template. While this method gets the job done, the code is not ve ...

Material UI does not support the inline attribute for applying CSS properties

Trying to adjust the CSS for Material-UI When setting the width, everything works fine. However, when attempting to set display inline, an error occurs ---> "inline is not defined" Can anyone provide guidance on how to resolve this issue? Sharing my cod ...

JavaScript function failing to validate password

While engaging in an online game where the objective is to uncover a password by inspecting the page source or element, I encountered a puzzling line: if(el.value == ""+CodeCode+""). My assumption is that el.value represents my guess, and it indicates that ...

Is it safe to remove npm packages that have been labeled as NOTUSED by npm-check without causing any issues

In the process of refactoring an Angular/Ionic project that I recently inherited, I decided to run a tool called npm-check. Much to my surprise, it detected several dependencies labeled as NOTUSED. The tool advised to "Check your code before removing as de ...

Amplify encounters the "Failed to load resource: the server responded with a status of 400" issue

I encountered an error while using Amplify, although the build was completed successfully. Failed to load resource: the server responded with a status of 400 manifest.json:1 The system is functional in the local environment. Below is the Package.json scri ...

The dynamic duo: Formik meets Material-UI

Trying to implement Formik with Material-UI text field in the following code: import TextField from '@material-ui/core/TextField'; import { Field, FieldProps, Form, Formik, FormikErrors, FormikProps } from 'formik'; import ...

Invoking a greasemonkey script when a user interacts with a button

For a script I wrote, I added an extra column and link in each row. However, the issue is that I want the links to trigger a function in my greasemonkey script and pass a variable to it. I have learned that because greasemonkey operates in a sandbox, achi ...