动态更新的ng2图表

时间:2016-08-22 11:12:13

标签: angular charts ng2-charts

是否可以动态更新chart中的任何ng2-charts?我知道还有其他库,如angular2-highcharts,但我想使用ng2-charts来处理它。主要问题是如何在点击按钮后重绘chart?我可以调整窗口大小并更新数据,因此必须手动执行此操作。

https://plnkr.co/edit/fXQTIjONhzeMDYmAWTe1?p=preview

7 个答案:

答案 0 :(得分:7)

一个好方法是抓住图表本身,以便使用API​​重绘它:

"[object Array]"

答案 1 :(得分:6)

我弄明白,也许它不是现有的最佳选择,但它确实有用。我们无法更新现有的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; } 并添加新点。我们甚至可以获得更好的效果,关闭图表动画。

解决问题的功能:

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

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

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

# Load mod_jk module
# Update this path to match your modules location
LoadModule jk_module "C:/Program Files/BitNami WAMPStack/apache2/modules/mod_jk.so"

# Where to find workers.properties
# Update this path to match your conf directory location
JkWorkersFile C:/softwares/apache-tomcat-7.0.42/conf/workers.properties

# Where to put jk logs
# Update this path to match your logs directory location
JkLogFile C:/MyProject/mod_jk.log

# Set the jk log level [debug/error/info]
JkLogLevel info

# Select the log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y]"

# JkOptions indicate to send SSL KEY SIZE,
JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

# JkRequestLogFormat set the request format
JkRequestLogFormat "%w %V %T"

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://localhost$1 [R,L] 

# Send everything for context /myProject to worker ajp13
JkMount /myProject ajp13
JkMount /myProject/* ajp13 

答案 2 :(得分:4)

最近我不得不使用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;
    }    
}

我确定这是正确的做法。

答案 3 :(得分:3)

这是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>

,并且您在ts组件中订阅了返回可观察数据的服务,在这种情况下,我们将计算一个Firestore字段值,该字段将解析为一个数字以及所购买课程/产品的标题

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并返回可观察值的service 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

答案 4 :(得分:2)

**这对我有用 - 用饼图:*

<强> 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';

在导出类的声明部分:

@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();

答案 5 :(得分:1)

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

Angular更新图表,变量或引用必须更改。当您只更改数组元素的值时,变量和引用未更改。 See also Github

答案 6 :(得分:0)

经过一段时间的搜索,我找到了这篇文章。然后,我尝试了本文中提到的所有解决方案,但都无法正常工作。最后,我使用了动态组件。

我向组件提供了动态数据,该数据已动态添加到父组件。我写了whole process只是为了避免您遇到挑战。