2017-02-13 27 views
1

我正在使用ng2-charts並需要更多控制。ng2-charts訪問chartjs對象以應用chartjs函數

xAxis值範圍應該動態變化。爲了實現這一點,我需要訪問由ng2-charts使用的圖表對象。然後,我可以做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導入的一部分。

回答

0

該解決方案直接在指令上使用@ViewChild並強制重新繪製每個新數據。 [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({}); 
Dataadding和移除本身的@input對象 lineChartData這是在HTML像這樣定義上完成