Chartjs-In ng 2 chart during the load an undefined legend gets created automatically ,Is there any way to remove it?

0👍

You can make use of the legend filter function, here you can check if the data array has a length of 0, if this is the case hide it like the example below:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 0],
        borderWidth: 1,
        backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
      },
      {
        label: '# of Counts',
        data: [],
        borderWidth: 1,
        backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        labels: {
          filter: (legendItem, chartData) => (chartData.datasets[legendItem.datasetIndex].data.length !== 0)
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

Leave a comment