ionic 3 angular chartjs canvas vanishes on show hide

Viewed 969

i am having a ionic 3 angular app and using chart.js to show a doughnut chart. Nothing advance just a simple doughnut chart with basic data. The chart is rendered the standard way using canvas as follows:

<canvas #doughnutCanvas></canvas>

It comes fine. Now the problem starts when i added a show hide of the ion-card-content to flip the view. The implementation looks like below:

  <ion-card-content  *ngIf="expanded == false" style="padding-bottom:0">
      <ion-row no-padding>
          <ion-col col-auto no-padding>
              <canvas #doughnutCanvas></canvas>
          </ion-col>
      </ion-row>
  </ion-card-content>
  <ion-card-content  *ngIf="expanded == true" style="padding-bottom:0">
      <ion-list>
          ....
      </ion-list>
  </ion-card-content>

show when i hit a button i change the expanded from false to true as a result the view changes and shows a list. However, when i hit the button again to toggle the value from true to false the chart does not render. just a blank ion-card-content. As other contents on the chart page comes fine so this is something to do with chartjs only. Please advise

2 Answers

The problem is that the chart doesn't get re-rendered when the canvas it created and ngIf completely removes/adds the dom.

Either change your ngIf to [hidden] or set chart.js to re-render the chart when expanded changes from false to true.

  <ion-card-content  [hidden]="expanded == false" style="padding-bottom:0">
                    <ion-row no-padding>
                      <ion-col col-auto no-padding>
                        <canvas #doughnutCanvas></canvas>
                     </ion-col>
                     </ion-row>
   </ion-card-content>

This should work:

<ion-card-content   [hidden]="expanded" style="padding-bottom:0">
                    <ion-row no-padding>
                      <ion-col col-auto no-padding>
                        <canvas #doughnutCanvas></canvas>
                     </ion-col>
                     </ion-row>
   </ion-card-content>
  <ion-card-content  [hidden]="!expanded" style="padding-bottom:0">
                   <ion-list>
                            ....
                    </ion-list>
   </ion-card-content>
Related