how to hide specific dataset based on condition chartjs angular

Viewed 620

I have created a simple doughnut chart using chartjs plugin in angular like the given screenshot below

1

now when the chart loads if the dataset value below 100 it should automatically hide like below

2

here is my complete code https://stackblitz.com/edit/ng2-charts-legend-with-value-hide

tried this piece of code which was taken from this reference https://jsfiddle.net/beaver71/00q06vjp/

pieChartData.data.forEach(function(ds) {
    ds.hidden = !ds.hidden;

still no luck please help me to solve this issue

3 Answers

Update your ngOnInit on stackBlitz and see if this is what you want

ngOnInit() {
    const othis = this;
    this.pieChartData.forEach((data, i) => {
      if (data < 100) {
        othis.pieChartData.splice(i, 1);
      }
    })
  }

If you have access to the chart object from the wrapper you can hide the dataset this way:

if (data < 100) {
  chartObject.getDatasetMeta(2).hidden = true
  chartObject.update()
}

But im not fammiliar with the ng wrapper so I dont know if they exposed the chart object. If this is not the case you might want to look into using only the normal lib and writing your own wrapper component.

Edit: According to this thread it is possible to acces the chart object (ng2-charts access base chart object)

When you set your data, you probably have something like this:

this.barChartData = [
    { data:[1, 2, 3], label: 'legend'}
];

you can add one parameter entitled hidden :

this.barChartData = [
    { data:[1, 2, 3], label: 'legend', hidden: true }
];

instead of "true", you can probably run a test and beforehand and store the result in a variable.

Related