【问题标题】:How do you change the tick options for ng2-charts at runtime?如何在运行时更改 ng2-charts 的刻度选项?
【发布时间】:2021-05-07 18:19:49
【问题描述】:

https://stackblitz.com/edit/ng2-ch

如何在运行时更新刻度选项?它没有任何效果。

【问题讨论】:

    标签: angular ng2-charts


    【解决方案1】:

    您必须在onClick() 内再次更新整个 lineChartOptions 对象才能看到效果:

    相关TS

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { ChartDataSets, ChartOptions, TickOptions } from 'chart.js';
    import { Color, Label } from 'ng2-charts';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      public lineChartData: ChartDataSets[] = [
        { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
      ];
      public lineChartLabels: Label[] = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
      public lineChartOptions: (ChartOptions & { annotation: any }) = {
        responsive: true,
        scales: {
          yAxes: [
            {
              position: 'right',
              ticks: {
                max: 50,
                min: 10
              }
            }
          ]
        }
      };
      public lineChartColors: Color[] = [
        {
          borderColor: 'black',
          backgroundColor: 'rgba(255,0,0,0.3)',
        },
      ];
      public lineChartLegend = true;
      public lineChartType = 'line';
      public lineChartPlugins = [];
    
      constructor() { }
    
      ngOnInit() {
      }
    
      onClick() {
        const newMin=10;
        const newMax=30;
        const tickOptions: TickOptions = {
          newMin,
          newMax
        };
    
        let original = this.lineChartOptions;
    //    this.lineChartOptions = null;
    
    //    original.scales.yAxes[0].ticks = tickOptions;
    //    original.scales.yAxes[0].position = 'right';
    //    this.lineChartOptions = original;
    
      this.lineChartOptions = {
        responsive: true,
        scales: {
          yAxes: [
            {
              position: 'right',
              ticks: tickOptions
            }
          ]
        }
      };
    
        console.log("Updated scales");
      }
    }
    

    现有stackblitz here

    【讨论】:

    • 为什么在没有替换对象的情况下无法检测到变量变化?它没有办法告诉对象的任何部分都发生了变化吗?
    • 这是一个与 ng2-charts 相关的特性,而不是 Angulat 我想说的......我们都会喜欢的 OSS 的一部分 :)
    • 我问是因为 Angular 不应该检测到变量的变化吗?否则 angular 的用户将不得不替换对象。我还不是一个有角度的人,但从在线资源看来,角度应该看到变化而不需要更换实例。
    【解决方案2】:

    这是我更新图表选项(在我的例子中是比例)的解决方案:

    let options =  this.lineChartOptions;    
    options.scales.xAxes[0].ticks.min = 0;
    options.scales.xAxes[0].ticks.callback = (v: number) => v * -1;      
    this.lineChartOptions = {...options};
    

    之后无需更新图表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 2013-04-26
      • 2016-12-28
      • 1970-01-01
      • 2018-06-22
      • 2022-01-20
      • 2016-11-23
      相关资源
      最近更新 更多