首页 > 解决方案 > 在 Angular 10 中使用 chart.js 创建多个动态堆叠图表?

问题描述

我正在尝试以角度创建多个图表,但我不确定我尝试实现 will 的方式是否正确,并且我无法创建多个图表并将其替换为另一个

 <div *ngIf="chartData.length !== 0">
      <app-limus-utilisation-chart
      *ngFor="let entity of chartData" [chartdata]="entity"
      ></app-limus-utilisation-chart>
    </div>

图表组件.ts

getStackedChart() {
        const canvas: any = document.getElementById('canvas1');
        const ctx = canvas.getContext('2d');
        
        var data = {
          labels: this.chartdata.buyernames,
         
          datasets: [{
            label: 'Utilised Limit',
            data: this.chartdata.utilisedlimitData,
            backgroundColor: '#22aa99'
          }, {
            label: 'Available Limit',
            data: this.chartdata.availablelimit,
            backgroundColor: '#994499'
          }]
        }
    
        chartJsLoaded$.pipe(take(1)).subscribe(() => {
          setTimeout(() => {
            this.myChart = new Chart(ctx, {
              type: 'bar',
              data: data,
              options: {
                tooltips: {
                  mode: 'index',
                  intersect: true,
                  position: 'custom',
                  yAlign: 'bottom'
                },
                scales: {
                  xAxes: [{
                    stacked: true
                  }],
                  yAxes: [{
                    stacked: false,
                    display: false
                  }]
                }
              }
            });
          })
    
        })
      }

我尝试了两种方法

使用 view child 未创建图表,创建了 getElementById 图表,但第二个图表替换了第一个图表。但我想要两个并排的堆叠图表如何实现这一点

并且当前图表采用低于 100 的值,但根据我的实际要求,我需要显示类似 (1000000, 700000) 的提示金额,也就是货币格式

像这样我试图实现 https://stackblitz.com/edit/angular-chart-js-j26qhm?file=src%2Fapp%2Fapp.component.html

请给建议

得到答案后,我取得了一些成就

https://stackblitz.com/edit/angular-chart-js-tyggan

标签: javascriptchart.jsng2-chartsangular10

解决方案


问题是这里的这一行:

    const canvas: any = document.getElementById('canvas1');

您在页面上有多个具有该 ID 的元素(因为您执行了 *ngFor),因此它始终将自身附加到页面上的第一个元素。

与其使用 getElementByID,不如使用 Angular 的内置@ViewChild.

像这样:

chart.component.html:

<canvas #stackchartcanvas></canvas>

chart.component.ts:

@ViewChild("stackchartcanvas") myCanvas: ElementRef<HTMLCanvasElement>;
....
....
....
getStackedChart() {
    const canvas = this.myCanvas.nativeElement;
}

Stackblitz:https ://stackblitz.com/edit/angular-chart-js-kny4en?file=src%2Fapp%2Fchart.component.ts

(此外,在您的原始代码中,this.chartData.push()每次单击复选框时都会运行,即使复选框为假,但这是一个不同的、不相关的问题,该问题也已得到修复。)


推荐阅读