Skip to content Skip to sidebar Skip to footer

Private Members Are Accessible In Angular 2 Decorators

Consider this code: export class Hero { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '

{{title}}

Solution 1:

In JavaScript there is no such thing as private variables. Keywords like private are just used by the TypeScript transpiler to enforce constraints before transpilation. Once the code is transpiled into JavasScript, the name property is a visible member of the Hero class.

Solution 2:

The private keyword in typescript is just used for compile time checking and doesn't actually restrict access to anything at runtime. The typescript compiler isn't checking your templates so it's not catching the issue.

I believe some IDE's (VS Code and WebStorm) are working on type checking your templates but for now you are on your own

Solution 3:

Angular2 states referring private variables within templates as a correct way. See cheat-sheet: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter.

So go ahead! And enable encapsulation to your components not exposing every variables as public.

Post a Comment for "Private Members Are Accessible In Angular 2 Decorators"