【问题标题】:ng2-charts access base chart objectng2-charts 访问基本图表对象
【发布时间】:2016-08-22 16:05:22
【问题描述】:

我在我的 ionic 2 项目中使用ng2-charts 来绘制折线图。我需要在 (chartClick) 事件中访问图表数据点集合。为此,我需要访问图表的基本 chart.js 对象。有没有办法可以访问图表对象?

HTML:

<base-chart class="chart"
        [data]="chartData"
        [labels]="chartLabels"
        [options]="lineChartOptions"
        [colours]="lineChartColours"
        [legend]="lineChartLegend"
        [chartType]="chartType"
        (chartClick)="chartClicked($event)"></base-chart>

打字稿:

chartClicked(e: any) {
    var chart = //reference to base chart object.
    var points = chart.getPointsAtEvent(e);
    alert(chart.datasets[0].points.indexOf(points[0]));
}

【问题讨论】:

    标签: chart.js ng2-charts


    【解决方案1】:

    最终设法解决了这个问题。使用 app.getComponent() 方法获取对 ng2-chart 对象的引用,然后对内部 chart.js 图表对象进行引用。

    HTML:(添加元素 id 'mylinechart')

    <base-chart id="mylinechart" class="chart"
        [data]="chartData"
        [labels]="chartLabels"
        [options]="lineChartOptions"
        [colours]="lineChartColours"
        [legend]="lineChartLegend"
        [chartType]="chartType"
        (chartClick)="chartClicked($event)"></base-chart>
    

    打字稿:

    constructor(private app: IonicApp) {
    }
    
    chartClicked(e: any) {
        var chartComponent = this.app.getComponent('mylinechart'); //ng2-chart object
        var chart = chartComponent.chart; //Internal chart.js chart object
        console.log(chart.datasets[0].points.indexOf(e.activePoints[0]));
    }
    

    2017 年 2 月 14 日更新@ViewChild

    如果上述方法不起作用(由于角度更新),请尝试此操作。我没有测试这个确切的代码,因为我没有确切的源代码了。在我当前的项目中,我使用的是 angular 2.4,所以我知道 @ViewChild 有效。

    将 HTML 标记更改为:

    &lt;base-chart #mylinechart class="chart" etc..(注意#mylinechart

    键入脚本:

    顶部:import { Component, ViewChild } from '@angular/core';

    然后在你的组件类中:

    @ViewChild('mylinechart')
    private chartComponent: any;
    
    constructor(private app: IonicApp) {
    }
    
    chartClicked(e: any) {
        var chart = this.chartComponent.chart; //Internal chart.js chart object
        console.log(chart.datasets[0].points.indexOf(e.activePoints[0]));
    }
    

    基本上,@ViewChild 会为您提供对模板中标记为“#mylinechart”的组件的引用。用@ViewChild 装饰chartComponent 变量可以通过该变量访问图表组件。请注意,@ViewChild 返回的引用仅在 'ngAfterViewInit' 生命周期事件之后可用。由于我的用例是图表“点击”事件,因此我可以放心地假设该视图已在那时初始化。

    参考:Angular @ViewChild

    【讨论】:

    • 这对我不起作用。 getComponent 似乎已弃用。我用 ViewChild 试过这个,但图表不是 chartcomponent 的有效属性
    • 我已经通过@ViewChild 发布了对答案的更新。请查看新方法是否适合您并在此处回复。还要检查是否需要使用“ngAfterViewInit”事件。
    • 我以前也这样试过。但那行不通。但我找到了另一种方法来归档所需的结果:stackoverflow.com/a/42212587/1093816(基本上是查看子类 BaseChartDIrectory 并使用其 ngOnChange 方法更新图表。感谢您的反馈!
    • 我正在使用它来访问它并且它可以工作:@ViewChild(BaseChartDirective) public chart: BaseChartDirective; 如果您需要强制刷新以便再次考虑选项:this.chart?.ngOnChanges({});
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2021-04-25
    • 2018-02-19
    • 2016-10-31
    • 2019-02-21
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多