Angular2 - should private variables be accessible in the template?

Edit: This answer is now incorrect. There was no official guidance on the topic when I posted it, but as explained in @Yaroslov's (excellent, and correct) answer, this is no longer the case: Codelizer now warns and AoT compilation will fail on references to private variables in component templates. That said, on a conceptual level everything here remains valid, so I'll leave this answer up as it seems to have been helpful.


Yes, this is expected.

Keep in mind that private and other access modifiers are Typescript constructs, whereas Component/controller/template are angular constructs that Typescript knows nothing about. Access modifiers control visibility between classes: Making a field private prevents other classes from having access to it, but templates and controllers are things that exist within classes.

That's not technically true, but (in lieu of understanding how classes relate to decorators and their metadata), it might be helpful to think of it this way, because the important thing (IMHO) is to shift from thinking about template and controller as separate entities into thinking of them as unified parts of the Component construct - this is one of the major aspects of the ng2 mental model.

Thinking about it that way, obviously we expect private variables on a component class to be visible in its template, for the same reason we expect them to be visible in the private methods on that class.


UPD

Since Angular 14, it is possible to bind protected components members in the template. This should partially address the concern of exposing internal state (which should only be accessible to the template) as the component's public API.


No, you shouldn't be using private variables in your templates.

While I like the drewmoore's answer and see perfect conceptual logic in it, implementationwise it's wrong. Templates do not exist within component classes, but outside of them. Take a look at this repo for the proof.

The only reason why it works is because TypeScript's private keyword doesn't really make member private. Just-in-Time compilation happens in a browser at runtime and JS doesn't have any concept of private members (yet?). Credit goes to Sander Elias for putting me on the right track.

With ngc and Ahead-of-Time compilation, you'll get errors if you try accessing private members of the component from template. Clone demonstration repo, change MyComponent members' visibility to private and you will get compilation errors, when running ngc. Here is also answer specific for Ahead-of-Time compilation.