角度5重置图表js bar在同一个组件中

时间:2018-06-07 14:54:06

标签: angular angular5 chart.js

我有组件显示我的产品的细节我在组件中使用了horizo​​ntalBar图表,但是当我查看其他产品时,它会保持透明的字符栏,并且新栏会附加到它。我试图空图表栏值,我也删除了artingArr,但它不工作如何重置图表并重新绘制产品数据?

我的图表是这样的: 在ngAfterinit():

    for (let rate of this.product.product_ratings) {
      this.sum += rate.rating;
      this.ratingArr.push(rate.rating);
      let n = this.product.product_ratings.length;
      let nn = this.sum / n;
      this.product.peopleCount = n;
      this.product.between = Math.round(nn * 10) / 10;
    }


   new Chart(<HTMLCanvasElement>document.getElementById("user-rev-chart"), {
      type: 'horizontalBar',
      data: {
        labels: ["5 star", "4 star", "3 star", "2 star", "1 star"],
        datasets: [
          {
            fill: true,
            label: false,
            backgroundColor: ["#a1a7b3", "#a1a7b3", "#a1a7b3", "#a1a7b3", "#a1a7b3"],
            data: [this.fivestar, this.fourstar, this.threestar, this.twostar, this.onestar]
          }
        ]
      },
      options: {
        maintainAspectRatio: false,
        responsive: false,
        legend: {display: false},
        title: {
          display: false,
          text: ''
        },
        scales:
          {
            yAxes: [{
              // barPercentage: 0.4,
              barThickness: 20,
              barPercentage: .5,
              categoryPercentage: .2,
              isFixedWidth: true,
              //Number - Pixel width of the bar
              barWidth: 20,
              gridLines: {
                display: false
              },
              ticks: {
                min: 0,
                stepSize: 1,
                fixedStepSize: 1,
              }
            }],
            xAxes: [{
              display: false,
              gridLines: {
                display: false
              },
              ticks: {
                min: 0,
                stepSize: 1,
                fixedStepSize: 1,
              }
            }],
          }
      }
    });

ngInit():

  ngOnInit() {

    if (this.isActive() && this.auth.isAuthenticated()) {
      this.changeCaptcha();
    }
    this.all = null;
    this.cur = null;
    this.onestar = null;
    this.twostar = null;
    this.threestar = null;
    this.fourstar = null;
    this.fivestar = null;
    this.ratingArr = [];


  }

1 个答案:

答案 0 :(得分:1)

你必须获得2d上下文。

模板:

<div class="chart-container" fxFlex="80">
      <canvas id="currency"></canvas>
</div>

组件:

  private displayCurrencyGraph(currencyEntry: CurrencyEntry) {
    const currencyCanvas: any = document.getElementById('currency');
    const currencyCanvasContext = currencyCanvas.getContext('2d');
    ChartBuilder.buildChartLine(currencyCanvasContext,this.data );
  }

ChartBuilder:

static buildChartLine(canvasContext, data){
    new Chart(canvasContext, {
      type: 'line',
      data: {data} 
}

从您的代码中,您缺少来自画布的getContext('2d')调用。如果你添加它,它应该工作。

您必须在上下文中调用destroy()方法,然后分配新数据集。