Chartjs:如何在Ionic 4中切换图表的可见性

时间:2019-12-28 14:41:15

标签: javascript ionic-framework chart.js ionic4

我目前有2个图表-1个饼图和1个条形图都使用带有Ionic 4 / Angular的ChartJS完成。我想这样做,以便当我单击一个按钮时,它将在两个图表之间切换。最初,当我单击按钮进行更改时,图形会切换。但是,当我将鼠标悬停在图表上时,图表会继续同时显示(就像它们在同一画布上相互重叠一样)。

这是我的代码:

.html

<ion-content>
  <ion-list-header color="light">Vertical Bar Chart</ion-list-header>
  <ion-card class="welcome-card">
    <ion-card-header>
      <ion-card-subtitle>Number of Viewers per season for</ion-card-subtitle>
      <ion-card-title>Game of Thrones</ion-card-title>
    </ion-card-header>
    <ion-card-content>
        <canvas #barChart></canvas>
    </ion-card-content>
  </ion-card>

  <ion-grid>
    <ion-row>
      <ion-col style="text-align:center;">
        <ion-button (click)="viewBarChart()">Bar Chart</ion-button>
      </ion-col>
      <ion-col style="text-align:center;">
        <ion-button (click)="viewPieChart()">Pie Chart</ion-button>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

.ts文件

createBarChart() {
    this.bars = new Chart(this.barChart.nativeElement, {
      type: 'bar',
      data: {
        labels: ['S1', 'S2', 'S3', 'S4', 'S5', 'S6', 'S7', 'S8'],
        datasets: [{
          label: 'Finished Tasks',
          data: [2.5, 3.8, 5, 6.9, 6.9, 7.5, 10, 17],
          backgroundColor: 'rgb(38, 194, 129)', // array should have same number of elements as number of dataset
          borderColor: 'rgb(38, 194, 129)',// array should have same number of elements as number of dataset
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  }


viewPieChart(){
    this.bars = new Chart(this.barChart.nativeElement, {
      type: 'pie',
      data: {
        labels: ['Incomplete', 'In Progress', 'Finish', 'Overdue'],
        datasets: [{
          label: 'Number of Tasks',
          data: this.pieChartData,
        }]
      }
    });

    this.bars.update();
  }

viewBarChart(){
    this.bars = new Chart(this.barChart.nativeElement, {
      type: 'pie',
      data: {
        labels: ['Incomplete', 'In Progress', 'Finish', 'Overdue'],
        datasets: [{
          label: 'Number of Tasks',
          data: [14, 1, 9, 2],
          backgroundColor: 'rgb(38, 194, 129)',          
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });

    this.bars.update();
  }

ionViewDidEnter(){
    this.createBarChart();
}

1 个答案:

答案 0 :(得分:1)

添加一个功能以从画布中删除任何现有图表:

destroyChart() {
 if(this.bars) {
    this.bars.destroy()
 }
}

在对new Chart进行任何调用之前立即调用此函数

也可以将this.bars重命名为this.currentChart

请参见https://www.chartjs.org/docs/latest/developers/api.html#destroy