Skip to content

Commit

Permalink
Merge branch 'fix-chart-redraw-issue' of git://github.com/m0t0r/ng2-c…
Browse files Browse the repository at this point in the history
…harts into m0t0r-fix-chart-redraw-issue
  • Loading branch information
valorkin committed Jan 17, 2017
2 parents ce5011c + 905183b commit 96cda81
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
1 change: 0 additions & 1 deletion demo/src/app/components/charts/line-chart-demo.ts
Expand Up @@ -13,7 +13,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
29 changes: 24 additions & 5 deletions src/charts/charts.ts
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

0 comments on commit 96cda81

Please sign in to comment.