动态更新ng2图表



是否可以动态地从ng2-charts更新任何chart ?我知道有其他库像angular2-highcharts,但我想处理它使用ng2-charts。主要问题是我如何重新绘制chart,按钮点击后?我可以调整窗口大小和数据将更新,所以它必须是任何选项手动执行。

https://plnkr.co/edit/fXQTIjONhzeMDYmAWTe1?p =预览

一个好方法是掌握图表本身,以便使用API重新绘制它:

export class MyClass {
 @ViewChild( BaseChartDirective ) chart: BaseChartDirective;
  private updateChart(){
   this.chart.ngOnChanges({});
  }
}

我明白了,也许这不是现有的最佳选择,但它有效。我们不能更新现有的chart,但我们可以创建一个新的,使用我们现有的chart并添加新的点。我们甚至可以得到更好的效果,关闭动画的图表。

<年代>解决问题的函数:

updateChart(){
   let _dataSets:Array<any> = new Array(this.datasets.length);
   for (let i = 0; i < this.datasets.length; i++) {
      _dataSets[i] = {data: new Array(this.datasets[i].data.length), label: this.datasets[i].label};
      for (let j = 0; j < this.datasets[i].data.length; j++) {
        _dataSets[i].data[j] = this.datasets[i].data[j];
      }
   }
   this.datasets = _dataSets;
}

现场演示:https://plnkr.co/edit/fXQTIjONhzeMDYmAWTe1?p=preview

@UPDATE: 正如@Raydelto Hernandez在下面的评论中提到的,更好的解决方案是:

updateChart(){
    this.datasets = this.dataset.slice()
}

最近我不得不使用ng2-charts,我在更新数据方面遇到了一个非常大的问题,直到我发现了这个解决方案:

<div class="chart">
        <canvas baseChart [datasets]="datasets_lines" [labels]="labels_line" [colors]="chartColors" [options]="options" [chartType]="lineChartType">
        </canvas>
</div>

这里是我的组件:

import { Component, OnInit, Pipe, ViewChild, ElementRef } from '@angular/core';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';
@Component({
    moduleId: module.id,
    selector: 'product-detail',
    templateUrl: 'product-detail.component.html'
})
export class ProductDetailComponent {
    @ViewChild(BaseChartDirective) chart: BaseChartDirective;
    private datasets_lines: { label: string, backgroundColor: string, borderColor: string, data: Array<any> }[] = [
        {
            label: "Quantities",
            data: Array<any>()
        }
    ];
    private labels_line = Array<any>();
    private options = {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    };

    constructor() { }
    ngOnInit() {
        this.getStats();
    }
    getStats() {
        this.labels_line = this.getDates();
        this._statsService.getStatistics(this.startDate, this.endDate, 'comparaison')
            .subscribe(
            res => {
                console.log('getStats success');
                this.stats = res;
                this.datasets_lines = [];
                let arr: any[];
                arr = [];
                for (let stat of this.stats) {
                    arr.push(stat.quantity);
                }
                this.datasets_lines.push({
                    label: 'title',
                    data: arr
                });
                this.refresh_chart();
            },
            err => {
                console.log("getStats failed from component");
            },
            () => {
                console.log('getStats finished');
            });
    }
    refresh_chart() {
        setTimeout(() => {
            console.log(this.datasets_lines_copy);
            console.log(this.datasets_lines);
            if (this.chart && this.chart.chart && this.chart.chart.config) {
                this.chart.chart.config.data.labels = this.labels_line;
                this.chart.chart.config.data.datasets = this.datasets_lines;
                this.chart.chart.update();
            }
        });
    }
    getDates() {
        let dateArray: string[] = [];
        let currentDate: Date = new Date();
        currentDate.setTime(this.startDate.getTime());
        let pushed: string;
        for (let i = 1; i < this.daysNum; i++) {
            pushed = currentDate == null ? '' : this._datePipe.transform(currentDate, 'dd/MM/yyyy');
            dateArray.push(pushed);
            currentDate.setTime(currentDate.getTime() + 24 * 60 * 60 * 1000);
        }
        return dateArray;
    }    
}

我相信这是正确的方法。

**这对我来说很有效-使用饼状图:*

Component.html:

 <canvas baseChart [colors]="chartColors" [data]="pieChartData" [labels]="pieChartLabels" [chartType]="pieChartType"></canvas>

Component.ts:

标题部分:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Chart } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts/ng2-charts';

在export类的声明部分:

@ViewChild(BaseChartDirective) chart: BaseChartDirective;
// for custom colors
public chartColors: Array<any> = [{
backgroundColor: ['rgb(87, 111, 158)', 'yellow', 'pink', 'rgb(102, 151, 185)'],
borderColor: ['white', 'white', 'white', 'white']
}];

在更新饼状图数据的块之后(使用服务/套接字或任何其他方式):

this.chart.chart.update();

这是在2020年,ng2-charts的示意图

npm i ng2-charts
ng generate ng2-charts-schematics:<type> <chart-name>

这将生成一个组件(例如名为times- buy的条形图)

times-bought.component.html

<div style="display: block; width: 40vw; height:80vh">
  <canvas baseChart
    [datasets]="barChartData"
    [labels]="barChartLabels"
    [options]="barChartOptions"
    [colors]="barChartColors"
    [legend]="barChartLegend"
    [chartType]="barChartType"
    [plugins]="barChartPlugins">
  </canvas>
</div>

,在你订阅的组件中,服务返回一个可观察的数据,在这个例子中,我们计数一个firestore字段值,我们将其解析为一个数字和标题course/product bought

times-bought.component.ts

import { Component, OnInit } from '@angular/core';
import { ChartDataSets, ChartOptions, ChartType } from 'chart.js';
import { Color, Label } from 'ng2-charts';
import { AdminService } from 'src/app/services/admin.service';
import { _COURSES, _BAR_CHART_COLORS } from  "../../../../settings/courses.config";//
@Component({
 selector: 'times-bought-chart', // Name this however you want
 templateUrl: './times-bought.component.html', 
 styleUrls: ['./times-bought.component.scss']
})
export class TimesBoughtComponent implements OnInit {
public barChartData: ChartDataSets[] = [
 { data: [0, 0, 0, 0], label: 'Times Bought', barThickness: 60, barPercentage: 0.1 }];
public barChartLabels: Label[] = _COURSES  // Array of strings
public barChartOptions: ChartOptions = {
  responsive: true,
  scales: { yAxes: [{ ticks: { beginAtZero: true } }] }
};
public barChartColors: Color[] = _BAR_CHART_COLORS // 
public barChartLegend = true;
public barChartType: ChartType = 'bar';
public barChartPlugins = [];
constructor(private adminService: AdminService) { }
ngOnInit() {
  this.adminService.getAllCourses().subscribe(
    data =>{
      this.barChartData[0].data = data.map(v=> parseInt((v.times_bought).toString())) // parse FieldValue to Int
      this.barChartLabels = data.map(v => v.title)
  })
}}

对firestore执行实际查询并返回一个可观察对象的服务ts文件

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Course } from '../interfaces/course.interface';
@Injectable({
  providedIn: 'root'
})
export class AdminService {
constructor(private db: AngularFirestore) { }
public  getAllCourses(){
  return this.db.collection<Course>('courses', ref =>
    ref.orderBy('times_bought', 'desc')).valueChanges()
}}

和settings/courses.config.ts

export const _COURSES = [
 'Title1',
 'Title2',
 'Title3',
 'Title4']
 export const _BAR_CHART_COLORS = [
 {
   borderColor: [
     'rgba(255,0,0,0.5)',
     'rgba(54, 75, 181, 0.5)',
     'rgba(114, 155, 59, 0.5)',
     'rgba(102, 59, 155, 0.5)'
   ],
   backgroundColor: [
     'rgba(255,0,0,0.3)',
     'rgba(54, 75, 181, 0.3)',
     'rgba(114, 155, 59, 0.3)',
     'rgba(102, 59, 155, 0.3)'
   ]
 }]

务必关闭ngOnDestroy的订阅。课程集合的可观察对象将在每次更新times_bought字段时发出一个新值,这将触发图表中的更新。唯一的缺点是颜色被绑定到一个特定的列/栏,所以如果一个标题超过了另一个,只有标题会改变位置,y轴会相应地更新,而不是颜色还要确保你包含node_modules/dist/Chart.min.js到你的web清单(在pwa service worker的情况下),或者作为一个脚本在你的index.html

动态更新ng2-charts中的任何图表都是可能的。例子:http://plnkr.co/edit/m3fBiHpKuDgYG6GVdJQD?p=preview

Angular的更新表、变量或引用必须改变。当你只是改变数组元素的值时,变量和引用不会改变。

相关内容

  • 没有找到相关文章

最新更新