Chart issue when using it inside a segment on Ionic2 project

251 Views Asked by At

I'm trying to use a chart (imported from Chart.js) controlled by a segment at Ionic2, but when I put the chart inside the segment condition, the following error occurs:

Runtime Error this.barCanvas is undefined

Outside the segment control, the chart works well.

This is my home.ts and home.html file:

//home.ts file
import {
  Component,
  ViewChild
} from '@angular/core';
import {
  NavController,
  Platform
} from 'ionic-angular';
import {
  Chart
} from 'chart.js';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  @ViewChild('public barCanvas') public barCanvas;

  public barChart: any;

  tipoGrafico: string = "geral";
  isAndroid: boolean = false;

  constructor(platform: Platform) {
    this.isAndroid = platform.is('android');
  }




  ionViewDidLoad() {

    this.barChart = new Chart(this.barCanvas.nativeElement, {

      //parameters of my graphic...

    });

  }

}
    <!-- home.html file -->
    <ion-header>
      <ion-navbar no-border-bottom>
        <ion-title>
          Segments
        </ion-title>
      </ion-navbar>

      <ion-toolbar no-border-top>
        <ion-segment [(ngModel)]="tipoGrafico">
          <ion-segment-button value="geral">
            Geral
          </ion-segment-button>
          <ion-segment-button value="dipositivo">
            Dispositivo
          </ion-segment-button>
        </ion-segment>
      </ion-toolbar>
    </ion-header>

    <ion-content>
      <div [ngSwitch]="tipoGrafico">
        <div *ngSwitchCase="'dispositivo'">
          -->
          <ion-card>
            Grafico semana -->
            <ion-card-content>
              <canvas #barCanvas></canvas>
            </ion-card-content>
          </ion-card>
        </div>
      </div>

    </ion-content>

    <ion-content>
      <div [ngSwitch]="tipoGrafico">
        <ion-list *ngSwitchCase="'geral'">
          <ion-item>
            <ion-thumbnail item-start>
              <img src="assets/img/teste.jpg">
            </ion-thumbnail>
            <h2>Geral</h2>
          </ion-item>
        </ion-list>
      </div>
    </ion-content>

I don't have much ability with these languages so any help will be welcome!

0

There are 0 best solutions below