Reputation: 31
I use chart.js and I load data with service from db. After reloading it's not shown, but when I press f12 to open the console it appears like nothing happened.
component ts:
import { Component } from '@angular/core';
import { ChartData } from 'chart.js';
import { IInventory } from 'src/app/models/inventory';
import { IStorage } from 'src/app/models/storage';
import { InventoryService } from 'src/app/services/inventory.service';
import { StorageService } from 'src/app/services/storage.service';
@Component({
selector: 'app-stocks-chart',
templateUrl: './stocks-chart.component.html',
styleUrls: ['./stocks-chart.component.scss']
})
export class StocksChartComponent {
stocks: IInventory[]
storages: IStorage[]
selectedStorage: string = ''
stocksData: ChartData<'doughnut'> = {
labels: [],
datasets: [
{ data: [] }
]
}
stocksLabels: string[]
constructor(inventory: InventoryService, storages: StorageService) {
inventory.getInventory().subscribe((res: IInventory[]) => {
this.stocks = res
res.map((item: IInventory) => {
if (this.stocksData.labels?.includes(item.productName)) {
this.stocksData.datasets[0].data[this.stocksData.labels.indexOf(item.productName)] += item.stock
} else {
this.stocksData.labels?.push(item.productName)
this.stocksData.datasets[0].data.push(item.stock)
}
})
})
}
}
html:
<canvas
baseChart
type="doughnut"
[data]="stocksData"
></canvas>
I don't know, maybe there's something because it draws before getting data. But anyway, why does it appear after the window resizes (and the chart is still showing even after I close the console)?
Upvotes: 3
Views: 121
Reputation: 494
I had the same problem with different chart. I solved it with different solutions.
1.in your chart component call onWidthResize
;
2.updateing chart size with updateSize()
method (for me this method was in zoomcharts)
@HostListener('window:resize', ['$event']) onWidthResize(e: any) {
this.innerWidth = window.innerWidth;
this.innerHeight = window.innerHeight; }
ngAfterViewInit() {
this.onWidthResize(null);
setTimeout(() => {
this.myChart.updateSize()
}, 500)
}
Upvotes: 0