Search code examples
angulartypescriptngx-charts

Ngx-charts multi series line-chart


I am trying to create a multi series line chart in angular using Ngx-chart module but currently am at a stand still with the following issue:

When sending Date() formatted data as the "name" (x-axis) field, the data are pre-formatted to a (non-localized) UTC string. The pre-formatting overrides the (optional) [xAxisTickFormatting] input field. Below is an image of how my graph looks like:

enter image description here

I have tried creating a custom xAxisTickFormatting function - it still doesn't work, below is the function.

tickFormatting(value): string {
    console.log(value);
    const date = new Date(value);
    const newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);

    const offset = date.getTimezoneOffset() / 60;
    const hours = date.getHours();

    newDate.setHours(hours - offset);

    return newDate.toLocaleString();
  }


</ngx-charts-line-chart
.....
[xAxistickFormatting]="tickFormatting.bind(this)"
>
</ngx-charts-line-chart>

I am fetching my graph data from a django api. This is how the data will be fetched, for easier understanding:

"data": [
        {
            "series": [
                {
                    "name": "2020-02-06T09:32:45.782Z",
                    "value": 1.0
                },
                {
                    "name": "2020-02-06T09:34:52.094Z",
                    "value": 0.0
                },
                {
                    "name": "2020-01-27T08:08:10.395Z",
                    "value": 1.0
                },
                {
                    "name": "2020-01-27T08:54:49.915Z",
                    "value": 0.0
                },
                {
                    "name": "2020-01-27T11:47:04.054Z",
                    "value": 1.0
                },
                {
                    "name": "2020-01-20T13:53:08.058Z",
                    "value": 1.0
                },
                {
                    "name": "2020-01-20T13:53:55.327Z",
                    "value": 1.0
                }
            ],
            "name": "Github"
        }
]

Can anyone help in fixing this bug?


Solution

  • The dates in the key name need to be converted to javascript date format for it to be able to use the default tickFormatting function for dates. So I created A function that takes in an array of object and convert all the dates in the key value name to javascript new date object. This is the typescript function that takes in my JSON api response and converts the dates in the key value name to javascript new date object

    dateConvert(value: []) {
        value.forEach((element: any) => {
          element.series.forEach((item: any) => {
            item.name = new Date(item.name);
          });
        });
      }
    

    This for anyone who might get into the same problem