Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  181] [ 2]  / answers: 1 / hits: 71776  / 7 Years ago, mon, march 6, 2017, 12:00:00

I'm trying to create dynamically a chart using ng2-chart,
I get information from an angular 2 service, when I change only labels of chart it works and when I change data only it works, but When I change both just data are updated in the chart. have any one an explication for this strange behavior.



my template :



<canvas baseChart height=130 width=180  
[data]=doughnutChartData
[labels]=doughnutChartLabels
[chartType]=doughnutChartType
(chartHover)=chartHovered($event)
(chartClick)=chartClicked($event)>
</canvas>


my class :



export class PlDoughnutComponent implements OnInit {

constructor(private homeService: TileServiceService) { }

ngOnInit() {
this.updatePLdoughnut();

}

public util : UtilService = new UtilService();
public doughnutChartLabels:string[] = ['Download Sales'];
public doughnutChartData:number[] = [0,0,100];
public doughnutChartType:string = 'doughnut';

public updatePLdoughnut(){

this.homeService.getTile().
then(res => {

this.doughnutChartLabels = res.PLtypes;
this.doughnutChartData = this.util.objectToIntArray(res.PLByTypes);

})
}
}

More From » angular

 Answers
182

Apparently, if you do not modify the original reference to the labels array, it seems to work, at least for me. I mean, if you want a completely different set of labels, you should do something like this:



In the template:



<canvas baseChart
[datasets]=lineChartData
[labels]=lineChartLabels
[options]=lineChartOptions
[chartType]='line'></canvas>


In the ts component:



this.lineChartLabels.length = 0;
for (let i = tempLabels.length - 1; i >= 0; i--) {
this.lineChartLabels.push(tempLabels[i]);
}


Or, using new ECMAScript syntax:



this.lineChartLabels.length = 0;
this.lineChartLabels.push(...tempLabels);


The key is maybe the this.lineChartLabels.length = 0; statement, which practically 'empties' your array by setting its length to 0, without modifying the reference.
Hope this helps!


[#58660] Friday, March 3, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katieh

Total Points: 692
Total Questions: 104
Total Answers: 104

Location: Armenia
Member since Sat, Dec 31, 2022
1 Year ago
;