问题
I am using ng2-charts and require more control.
The xAxis value range should change dynamically. To achieve this I need to get access to the Chart-Object used by ng2-charts. Then I can do this
Which basically boils down to two steps:
//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);
I tried this solution but it seems that getComponent() is deprecated. To circumvent this I tried to use @ViewChild (with and without ElementRef) which would result in property "chart" being undefined on the received object.
Looking into the chartjs implementation in ng2-charts I can see that the BaseChartDirective controls the generation of charts and stores the generated chart as a class property (this.chart). However I am not certain how to get access to this property in my component.
ng2-charts is a module and therefore part of my @NgModule imports.
回答1:
The solution was using @ViewChild on the directive directly and forcing a redraw with each new data. Dataadding and removing itself was done on the @Input object lineChartData
which is defined in the html like this: [datasets]="lineChartData"
Code:
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({});
来源:https://stackoverflow.com/questions/42211288/ng2-charts-access-chartjs-object-to-apply-chartjs-functions