Erico Souza
Erico Souza

Reputation: 276

Charts in Ionic 2

I need to create charts in an app, which uses Ionic 2. I searched the web but found some very scarce models. And also http://www.chartjs.org, but his documentation is very poor.

I mostly need donut charts, with click events. Or is it possible for me to have a click event on the chartjs donut chart? How can I do this?

Upvotes: 1

Views: 480

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32889

You should use ng2-charts which is a ChartJS wrapper for Angular 2/4.

Using this you can create a simple doughnut chart (with click event) as follows :

template

<div id="chart-container">
    <canvas baseChart 
          [chartType]="chartType"
          [data]="chartData"
          [labels]="chartLabels"
          (chartClick)="chartClicked($event)">
  </canvas>
</div>

component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  public chartType: string = 'doughnut';
  public chartLabels: Array<string> = ['Jan', 'Feb', 'Mar'];
  public chartData: Array<number> = [1, 1, 1];

  public chartClicked(e: any): void {
    if (!e.active.length) return; //return if not clicked on chart/slice
    alert('Clicked on Chart!');
  }

}

LIVE DEMO
( this shouldn't be too hard to implement in Ionic 2 )

note: this is just a basic example of a doughnut chart and you can customize it further to fit your need, following the official documentation.

Upvotes: 2

Related Questions