[英]ng2 charts - refresh pie chart
我正在使用 ng2-charts - https://github.com/valor-software/ng2-charts
我有一個餅圖,如果我在我的 component.ts 文件頂部聲明變量時對數據進行硬編碼,就像我的餅圖顯示的示例一樣。
但我顯然想讓餅圖字符數據動態化。 我可以通過一個服務(是一個數字)調用數據,將數字添加到數據數組中,餅圖不起作用。 但是,如果我執行控制台日志,則該數組會打印出我添加到其中的新數據/數字。
我需要以某種方式重新繪制表格。 想不通怎么辦
public pieChartLabels:string[] = ['Red Flags','Green Flags'];
public pieChartData: number[] = [200, 400];
public chartType:string = 'pie';
public redFlagsTotal: any;
public greenFlagsTotal: any;
constructor(private dataService:flagService) {
let component = this;
this.redFlagsTotal = this.dataService.getRedFlags().then(function(result){
component.redFlagsTotal = result.length;
console.log(component.redFlagsTotal);
component.pieChartData.push(component.redFlagsTotal);
console.log(component.pieChartData);
});
this.greenFlagsTotal = this.dataService.getGreenFlags().then(function(result){
component.greenFlagsTotal = result.length;
console.log(component.greenFlagsTotal);
component.pieChartData.push(component.greenFlagsTotal);
console.log(component.pieChartData);
});
}
您可以像這樣隱藏和顯示圖表一毫秒:
refreshChart(){
this.mychart.show = false;
setTimeout(()=>{
this.mychart.show = true;
},1);
}
在模板中使用比mychart.show
和*ngIf
像這樣:
<div style="display: block">
<canvas baseChart
*ngIf="mychart.show"
[data]="pieChartData"
[labels]="pieChartLabels"
[chartType]="pieChartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
在您的函數中,當您想要刷新圖表時,您可以使用refreshChart()
函數。
編輯:
如果您重新初始化數組,則字符應該自動更新,而不是這樣:
component.pieChartData.push(component.greenFlagsTotal);
做這個:
let temp = [...component.pieChartData, ...component.greenFlagsTotal];
component.pieChartData = [...temp];
解決了! 隱藏畫布,直到數據加載完畢。
<div *ngIf="pieChartData.length > 1" style="display: block">
<canvas baseChart
[data]="pieChartData"
[labels]="flagPieChartLabels"
[chartType]="chartType"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)"></canvas>
</div>
另一種使圖表數據動態化的方法是通過 ViewChild 綁定圖表指令,如下所示:
...
export class HomeComponent {
@ViewChild(BaseChartDirective)
public chart: BaseChartDirective;
void updateChart() {
this.chart.chart.update(); // This re-renders the canvas element.
}
現在,您可以updateChart
每次數據集更改時調用updateChart
以保持圖表最新!
使用 *ngIf 隱藏畫布重新加載整個組件。
似乎如果您推送數據和標簽然后在 1 毫秒后刪除它們,它將重新加載正確的圖表數據。
reloadChart(){
this.pieChartLabels.push('reload');
this.pieChartData.push(1);
setTimeout(() => {
this.pieChartData.pop();
this.pieChartLabels.pop();
},1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.