Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart.js chart does not display when inside an ngIf.

I have a simple scatter line chart within a bootstrap panel created with Chart.js. It works/displays perfectly fine until I put it inside an ngIf div. Has anyone come across this? Any idea on how to make the chart display? The point of the ngIf in my example is to only show the panel-body's content (which is the chart) once the variable chartData has been populated.

Here's my chart code (I've commented out the ngIf div):

<!--<div *ngIf="chartData.length">-->
    <div class="panel panel-primary" style="border-color: #464646;">
        <div class="panel-heading" style="border-color: #BBBBBB; height: 35px; padding-top: 3px;">
            <div style="float: left; margin-top: 5px;">Line Chart</div>
        </div>

        <div class="panel-body">
            <div>
                <canvas id="myChart" width="325" height="325"></canvas>
            </div>
        </div>
    </div>
<!--/div>-->
like image 570
Roka545 Avatar asked Oct 16 '25 12:10

Roka545


2 Answers

#myChart is not present in the DOM when you're trying to initialize the chart. Try with ng-show instead of ng-if.

Anyhow, it loook like you're not initializing the chart from the controller once the data is populated, like you should do.

Hope it helps.

like image 131
alejandromav Avatar answered Oct 19 '25 04:10

alejandromav


you have to create the Chart object only after the div is created, so call the function that create the Chart on the same place where you change the chartData.length instead of calling it right after the component is created

like image 37
Avraham Weinstein Avatar answered Oct 19 '25 02:10

Avraham Weinstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!