Using @ViewChild with non-selected elements in ion-segment


I have an ion-segment that will display different graphs (using Chart.js) when selected:

  <div [ngSwitch]="segment">
    <canvas *ngSwitchCase="'bpmGraph'" #bpmChart></canvas>
    <canvas *ngSwitchCase="'stepGraph'" #stepChart></canvas>

  <div padding>
    <ion-segment [(ngModel)]="segment">
      <ion-segment-button (click)="retrieve()" value="bpmGraph">
      <ion-segment-button (click)="retrieve()" value="stepGraph">

And I am grabbing the elements using @ViewChild:

segment: string = "bpmGraph"; // initial segment is bpm
@ViewChild('bpmChart') bpmCanvas: ElementRef;
@ViewChild('stepChart') stepCanvas: ElementRef;

Then later on graphing with the nativeElement:

let ctx = this.bpmCanvas.nativeElement.getContext("2d");
let bpmChart = new chart(ctx, {...});

The issue is that @ViewChild will only grab the initially selected canvas (in this case bpmCanvas) and all others will be null, as they are not selected by the segment. How can I get references to all canvas elements?


Can you try hiding the unused canvases instead of using ngSwitch?


Interestingly, it seems that the problem only existed with ionic run. When I build the app it seems to work fine.

I’ve noticed this for several features, actually. For example Angular 2 Http requests don’t work until the app is built.


did you find a solution for this problem ?
i have a problem like this on segment ( google map )


like @rapropos said change *ngSwitchCase for [hidden] tag (remember that the hidden condition should be the opposite of the existent one), in that way you will be able to get the references for your elements and the charts will be correctly rendered