I am trying to display a bar chart using chartJS in LWC. On the page load the chart bar doesn't appear. If i do inspect element then it appear. Below is the code -
JS -
@wire( getOpportunities ) getOpps( { error, data } ) {
if ( data )
{
this.aggResult = data;
console.log( JSON.stringify( this.aggResult ) );
var labelset = [];
var dataset = [];
for ( let key in this.aggResult )
{
if ( this.aggResult.hasOwnProperty( key ) )
{
this.labelset.push( this.aggResult[ key ].Name );
this.dataset.push( this.aggResult[ key ].Amount );
}
};
} else if ( error )
{
console.log( "Error: " + error );
}
}
renderedCallback() {
if ( this.isChartJsInitialized )
{
return;
}
this.isChartJsInitialized = true;
Promise.all( [
loadScript( this, chartjs + "/js/chart.js" ),
loadStyle( this, chartjs + "/css/style.css" )
] )
.then( () => {
this._buildChart( this.dataset, this.labelset );
} )
.catch( ( error ) => {
console.log( "error " + error );
} );
}
_buildChart( dataset, labelset ) {
let canvas = this.template.querySelector( "canvas.chart" );
let context = canvas.getContext( "2d" );
this.chart = new window.Chart( context, {
type: "bar",
responsive: true,
data: {
labels: this.labelset,
//[ "Red", "Blue", "Yellow", "Green", "Purple", "Orange" ],
datasets: [
{
label: 'Opportunities',
backgroundColor: "rgba(22, 50, 92)",
data: this.dataset,
//[ 12, 19, 3, 5, 2, 3 ]
borderColor: "rgba(22, 50, 92)",
fill: true,
pointBackgroundColor: "#26B99A",
pointBorderWidth: 2,
pointHoverRadius: 5,
pointRadius: 2,
bezierCurve: true,
pointHitRadius: 10
}
]
}
} );
}
HTML -
<template>
<template if:true={labelset}>
<div class="slds-box slds-theme_default custom-background">
<canvas class="chart" width="950" height="250" lwc:dom="manual"></canvas>
</div>
<div if:false={isChartJsInitialized} class="slds-col--padded slds-size--1-of-1"> ChartJs Not loaded yet </div>
</template>
</template>
On page load it looks like this
If i do inspect element , then the bar appears -
Is there anything i am doing wrong.