Chartjs-Angular Chart Js legends click event not working

0👍

You can check ng2-charts which is the Angular port of Chart.js. You can always try to get the Angular port of libraries as it will be easier to work with and won’t get surprised with not working things (Like not detecting changes in callbacks).

import { Component, OnInit } from "@angular/core";
import { ChartType } from "chart.js";
import { MultiDataSet, Label, Colors } from "ng2-charts";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  // Doughnut
  public doughnutChartLabels: Label[] = ["red", "pink"];
  public doughnutChartData: MultiDataSet = [[55, 45]];
  public colors = [
    {backgroundColor:['rgba(255, 0, 0, 1)','rgba(255, 0, 0, 0.1)']}
  ];
  public doughnutChartType: ChartType = "doughnut";
  options = {
    legend: {
      display: true,
      labels: {
        usePointStyle: true
      },
      onClick: (event, legendItem) => {
        console.log("This is working!");
      }
    },
    tooltips: {
      enabled: false
    },
    onClick: (evt, item) => {
      console.log('Clicked!')
    }
  };

  constructor() {}

  ngOnInit() {}
}

and you template is:

<div style="display: block;">
  <canvas baseChart 
    [data]="doughnutChartData"
    [labels]="doughnutChartLabels"
    [chartType]="doughnutChartType"
    [colors]="colors"
    [options]="options"
    >
  </canvas>
</div>

You can check the StackBlitz here: https://stackblitz.com/edit/ng2-charts-doughnut-template-yjugml2

Leave a comment