Skip to content

Commit

Permalink
fix(charts): Make charts dynamic and avoid re-rendering full chart on…
Browse files Browse the repository at this point in the history
… data change
  • Loading branch information
m0t0r committed Jan 10, 2017
1 parent 8d24ea5 commit 905183b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
29 changes: 24 additions & 5 deletions components/charts/charts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export class BaseChartDirective implements OnDestroy, OnChanges, OnInit {
[77, 83, 96]
];

@Input() public data:number[] | Array<number[]>;
@Input() public data:number[] | any[];
@Input() public datasets:any[];
@Input() public labels:Array<any> = [];
@Input() public options:any = {};
Expand Down Expand Up @@ -62,14 +62,19 @@ export class BaseChartDirective implements OnDestroy, OnChanges, OnInit {
}
}

public ngOnChanges(changes:SimpleChanges):any {
public ngOnChanges(changes: SimpleChanges): void {
if (this.initFlag) {
// Check if the changes are in the data or datasets
if (changes.hasOwnProperty('data') || changes.hasOwnProperty('datasets') || changes.hasOwnProperty('labels')) {
this.chart.data.datasets = this.getDatasets();
this.chart.data.labels = this.labels;
if (changes.hasOwnProperty('data') || changes.hasOwnProperty('datasets')) {
if (changes['data']) {
this.updateChartData(changes['data'].currentValue);
} else {
this.updateChartData(changes['datasets'].currentValue);
}

this.chart.update();
} else {
// otherwise rebuild the chart
this.refresh();
}
}
Expand Down Expand Up @@ -122,6 +127,20 @@ export class BaseChartDirective implements OnDestroy, OnChanges, OnInit {
return new Chart(ctx, opts);
}

private updateChartData(newDataValues: number[] | any[]): void {
if (Array.isArray(newDataValues[0].data)) {
this.chart.data.datasets.forEach((dataset: any, i: number) => {
dataset.data = newDataValues[i].data;

if (newDataValues[i].label) {
dataset.label = newDataValues[i].label;
}
});
} else {
this.chart.data.datasets[0].data = newDataValues;
}
}

private getDatasets():any {
let datasets:any = void 0;
// in case if datasets is not provided, but data is present
Expand Down
1 change: 0 additions & 1 deletion demo/components/charts/line-chart-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ export class LineChartDemoComponent {
];
public lineChartLabels:Array<any> = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
public lineChartOptions:any = {
animation: false,
responsive: true
};
public lineChartColors:Array<any> = [
Expand Down

0 comments on commit 905183b

Please sign in to comment.