【问题标题】:ng2-charts access chartjs object to apply chartjs functionsng2-charts 访问 chartjs 对象以应用 chartjs 功能
【发布时间】:2017-02-14 04:04:43
【问题描述】:

我正在使用 ng2-charts,需要更多控制。

xAxis 值范围应该动态变化。为此,我需要访问 ng2-charts 使用的 Chart-Object。那我就可以this

这基本上归结为两个步骤:

//Chart-Object
var barChartDemo = new Chart(ctx).Bar(barChartData, {
  responsive: true,
  barValueSpacing: 2
});
setInterval(function() {
//removing the first dataentry
  barChartDemo.removeData();
//adding new data
  barChartDemo.addData([dData()], "dD " + index);
  index++;
}, 3000);

我尝试了this 解决方案,但似乎不推荐使用 getComponent()。为了规避这一点,我尝试使用@ViewChild(带和不带ElementRef),这将导致在接收到的对象上未定义属性“chart”。

查看 ng2-charts 中的 chartjs 实现,我可以看到 BaseChartDirective 控制图表的生成并将生成的图表存储为类属性 (this.chart)。但是我不确定如何在我的组件中访问此属性。

ng2-charts 是一个模块,因此是我的 @NgModule 导入的一部分。

【问题讨论】:

    标签: angular chart.js ng2-charts


    【解决方案1】:

    解决方案是直接在指令上使用 @ViewChild 并强制对每个新数据进行重绘。数据添加和删除本身是在 @Input 对象 lineChartData 上完成的,该对象在 html 中定义如下:[datasets]="lineChartData"

    代码:

    import { BaseChartDirective } from 'ng2-charts/charts/charts';
    export class Example{
        @ViewChild(BaseChartDirective) baseChartDir: BaseChartDirective;
        public lineChartData: Array<any>;
    
        //call this function whenever you want an updated version of your chart
        this.baseChartDir.ngOnChanges({});
    

    【讨论】:

    • 我一直在尝试在条形图中设置渐变背景,但我需要一种方法来手动更新 ngAfterViewInit 中的底层图表。这很完美!
    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 2019-04-02
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多