HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptangularCritical

Angular2 - should private variables be accessible in the template?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
privatevariablesshouldangular2thetemplateaccessible

Problem

If a variable is declared private on a component class, should I be able to access it in the template of that component?

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

Solution

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.

Context

Stack Overflow Q#34574167, score: 272

Revisions (0)

No revisions yet.