如何使用ng2-charts在角度2的饼图中显示数据?

时间:2018-12-07 12:24:29

标签: angular typescript

如图所示,我可以实现饼图,但是如何在图表上显示数据 enter image description here

像这样 enter image description here

 <canvas baseChart  class="pie"
  [data]="Data"
  [labels]="Labels"
  [colors]="Colors"
  [chartType]="pieChartType">
</canvas>

 public Labels:string[]=['Female','Male'];
 public Data:any =[51,30];
 public pieChartType:string = 'pie';
 public Colors:any = 
 [
{
  backgroundColor: [      
  'green',
  'red'
  ]
  }
]; 

1 个答案:

答案 0 :(得分:0)

首先,您需要运行两个npm命令

npm install ng2-charts --save

npm install chart.js --save

重要提示:必须在应用程序中嵌入Chart.js!在您的index.html

<script src="node_modules/chart.js/src/chart.js"></script>

将此内容导入App.module.ts

import { ChartsModule } from 'ng2-charts';
imports: [ChartsModule]

Component.html

<div style="display: block">
  <canvas baseChart
          [data]="pieChartData"
          [labels]="pieChartLabels"
          [chartType]="pieChartType"
          (chartHover)="chartHovered($event)"
          (chartClick)="chartClicked($event)"></canvas>

Component.ts

public pieChartLabels: string[] = ['Male', 'Female'];
  public pieChartData: number[] = [51, 30];
  public pieChartType: any = 'pie';

  // events
  public chartClicked(e: any): void {
    console.log(e);
  }

  public chartHovered(e: any): void {
    console.log(e);
  }

此代码按预期工作。