3gwebtrain 3gwebtrain - 2 months ago 43x
TypeScript Question

Angular2 - should private variables be accessible in the template?

If a variable is declared

on a component class, should I be able to access it in the template of that component?

selector: 'my-app',
template: `
<h2>Hello {{userName}}</h2> // I am getting this name
export class App {
public title = 'Angular 2';
private userName = "Test Name"; //declared as private


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.