ngx-charts: select data on bar chart and change color via code

1.4k Views Asked by At

I am using ngx-charts for the firs time and I am creating a ngx-charts-bar-vertical chart.

I have created the chart successfully but I am wondering if it is possible to select one of the bars by the name value.

In particular, my data look like:

[
  {
    name: '2020-01-01',
    value: 13
  },
  {
    name: '2020-01-02',
    value: 27
  }
]

I'd like to know if it is possible to select a specific bar by name and change its color to make it more prominent.

The idea is that, because in my app there is a date picker, I'd like to use the selected date to highlight the value for that date in the chart.

I see that the vertical bar chart has several events associated (like select, activate), but I cannot seem to understand if these could be useful for what I need.

Also, if this is relevant, I can use different types of dates in my application, so if strings are not the best, i can easily work with JavaScript Date objects if needed (although I don't see any time-related option in the vertical bar chart docs, but I see it in the line chart one).

1

There are 1 best solutions below

0
On BEST ANSWER

Here is how I did it. I used the customColors property of vertical-bar-chart to set the color of the bar based on the value of one of its labels.

Basically, what I did was defining a customColors property within my chart class ts file, added it in the html as well, and then I can change the color of it based on a value I want.

As my values are dates, I can do something like this:

this.getTime().subscribe(time => {
  this.customColors = [
    {
        name: time.format('YYYY-MM-DD'),
        value: '#ff0000' // RED FOR THIS DATE ONLY
    }
  ];
});

In my app, this.getTime() gives me the current time from the date picker as Observable<moment.Moment>, and I can use this moment date object to format the way it is in the chart to "select" my bar and change its color.