I have a simple project that displays an Ionic segment in which there is a Chart.js barchart. I have no problem with displaying the chart itself, but trying to put the chart HTML inside Ionic segment gives me the following error:
ERROR TypeError: Cannot read property 'nativeElement' of undefined
at HomePage.webpackJsonp.203.HomePage.ionViewDidLoad (home.ts:19)
If I just move <canvas #barcanvas></canvas>
and place it almost anywhere else in the .html document, the chart displays nicely, but not inside the Ionic segment element.
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div padding>
<ion-segment [(ngModel)]="pet">
<ion-segment-button value="kittens">
Kittens
</ion-segment-button>
<ion-segment-button value="puppies">
Puppies
</ion-segment-button>
</ion-segment>
</div>
<div [ngSwitch]="pet">
<ion-list *ngSwitchCase="'puppies'">
puppies...
<canvas #barcanvas></canvas>
</ion-list>
<ion-list *ngSwitchCase="'kittens'">
kittens...
</ion-list>
</div>
</ion-content>
home.ts
import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Chart } from 'chart.js';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('barcanvas') barcanvas;
barChart: any;
constructor(public navCtrl: NavController) {
}
ionViewDidLoad() {
this.barChart = new Chart(this.barcanvas.nativeElement, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}
});
}
}