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


#1

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>

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

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?


#2

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


#3

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.


#4

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


#5

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