Is there a way to 'refresh' @ViewChild

I’m facing a very weird problem with ChartJS2 and Ionic that is related to the full page disappearing, only on iOS once in a while for no apparent reason, and with no errors. I can expand on whats happening, but for now let me ask a simpler question:

I think I am facing a problem with the fact that I am dynamically hiding/showing the chart based on user input and I’d like to refresh the handles to the DOM elements.

I get the DOM handles using

 @ViewChild('accGraph') accCanvas;
  @ViewChild('gyroGraph') gyroCanvas;

in the class definition.

the corresponding template:

<canvas #accGraph></canvas>
<canvas #gyroGraph></canvas>

Is there a way, subsequently, to refresh accCanvas and gyroCanvas?

I don’t know. The standard Angular response though would probably be: make a canvas component with an Input(), and pass the chart you want to display. Then with just one component and an *ngIf, you can hide or display charts dynamically, and you only need to use ViewChild once at most.

Another option would be to use [hidden] instead. Either way, I would strongly recommend against using @ViewChild on things that are not always in the DOM.

1 Like

Yup, I’ve tried hidden too - given it only hides and doesn’t remove. That did not change things.
Edit: What recommendation would you have as an alternate to @ViewChild?

Okay, I’ll investigate this approach too

Since this discussion happened, I became aware of an alternative strategy that directly addresses OP’s issue: use a setter instead of a variable:

Instead of:

@ViewChild('accGraph') accCanvas;

…do:

accCanvas: Canvas;
@ViewChild('accGraph') setAccGraph(c: Canvas) {
  this.accCanvas = c;
}

In my experience, this is robust in the face of ngIf taking the child element in and out of the DOM.

2 Likes