Chartjs-How do I open a dialog on clicking a Bar in the BarChart?

0๐Ÿ‘

โœ…

So after some time i figured it out.

import { Component, OnInit, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { BarChartService } from '../bar-chart.service';
import { barChartClass } from '../barChartClass';

@Component({
  selector: 'app-my-bar-dialog',
  templateUrl: './my-bar-dialog.component.html',
  styleUrls: ['./my-bar-dialog.component.css']
})
export class MyBarDialogComponent implements OnInit {

  client: string;
  tenant: string;

  constructor(public dialog: MatDialog, private barChartService: BarChartService) { }

  //First BarChart
  barChart: barChartClass;
  public barChartLabels: any;
  public barChartType: any;
  public barChartLegend: any;
  public barChartData: any;

  getBarChart(): void {
    this.barChartService.getMockBarChart().subscribe(
      barChart => this.barChart = barChart
    );
    this.barChartData = this.barChart.barChartData;
    this.barChartLabels = this.barChart.barChartLabels;
    this.barChartType = this.barChart.barChartType;
    this.barChartLegend = this.barChart.barChartLegend;
  }

  public barChartOptions = {
    scaleShowVerticalLines: false,
    responsive: true,
    events: ['mousemove', 'mouseout', 'click', 'touchstart', 'touchmove'],
    onHover: console.log('ttt'),
    onClick : () => {
      this.openDialog();

    },
    scales: {
      xAxes: [{
        stacked: true
      }],
      yAxes: [{
        stacked: true
      }]
    },
    legend: {
      display: true,
      position: 'right'
    },
    tooltips: {
      enabled: true,
      mode: 'point'
    }
  };

  openDialog(): void {
    const dialogRef = this.dialog.open(DialogData, {
      width: '250px',
      data: {client: this.client, tenant: this.tenant}
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed');
      this.client = result;
    });
  }
  ngOnInit() {
    this.getBarChart();
  }
}

@Component({
  selector: 'dialog-data',
  templateUrl: 'dialog-data.html',
  styleUrls: ['dialog-data.css']
})
export class DialogData {

  constructor(
    public dialogRef: MatDialogRef<DialogData>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

}

If you have further questions, you can ask me.

Leave a comment