Search code examples
angularprivateangular7viewchildangular-aot

Is it okay to mark a @ViewChild as private?


Is it okay to mark a ViewChild as private, if it's not being referenced in the template?

I have been able to do this, then build and serve with the '--prod' flag, and encountered no errors. I'm currently using Angular 7.

@ViewChild(HelloComponent) private helloComponent;

Here's a stackblitz to what I'm talking about:
https://stackblitz.com/edit/angular-vxbpuk?file=src%2Fapp%2Fapp.component.ts

I think I have the stackblitz using aot, but you could verify the same thing locally.

EDIT: I apologize for not bringing this up before, but there's this blurb from the angular doc that give me pause:

https://angular.io/guide/aot-compiler#phase-2-code-generation

Decorated component class members must be public. You cannot make an @Input() property private or internal.

But as @GCSDC already pointed out below, the Angular team seems to be using private members in their examples:
https://angular.io/guide/component-interaction#parent-calls-an-viewchild


Solution

  • It seems that yes, this is ok, as you may find it done also on the official angular fundamentals guides, at:

    Components & Templates > Component Interaction > Parent calls an @ViewChild():

    @ViewChild(CountdownTimerComponent) private timerComponent: CountdownTimerComponent;