Reputation: 6307
My code is as follow
@Component({
selector: 'my-app',
template: `
<ul>
<li *ngFor = 'let hero1 of heros2'>
{{hero1.name}}
</li>
</ul>
`})
export class AppComponent {
heros2 : any = [
new heross('lee', 'lee'),
new heross('lee1', 'lee1'),
];}
class heross{
private name : string;
constructor(name : string, details : string){
this.name = name;
}}
bootstrap(AppComponent);
why am I able to access name in the view and displaying name, provided that I have given it private keyword
Upvotes: 0
Views: 475
Reputation: 164277
If you'll try:
class A {
private x: number;
}
let a = new A();
console.log(a.x);
You'll get a compilation error:
Property 'x' is private and only accessible within class 'A'
The reason you're not getting that, I suspect (as I'm not an angular developer), is that you're having hero1.name
in a string so the typescript compiler doesn't treat hero1
as a variable.
I bet that if you try:
let obj = new heross("name", "details");
console.log(`heross.name: ${ obj.name }`);
Then you'll get the compilation error.
The difference being ${}
instead of {{}}
.
If however you're asking why that's accessible at runtime, then that's because there's no notion of visibility in javascript, it doesn't get pass the compiler.
There's a difference between the angular double curly brace ({{ }}
):
The double curly brace notation {{ }} to bind expressions to elements is built-in Angular markup
Which you don't need to put into ticks, you can just use regular single/double quotes.
And the javascript template literals (${ }
):
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification
More simply:
let x = 4;
console.log(`x={{ x }}`); // outputs 'x={{ x }}'
console.log(`x=${ x }`); // outputs 'x=4'
Upvotes: 2
Reputation: 10613
Because it's javascript at the end of the day. And Javascript language does not have a private
keyword.
Upvotes: 0
Reputation: 657721
Privacy is not enforced in TypeScript in general but only checked by static tools.
You can see the bindings in the view and the component class as a single unit, like the bindings in the template is part of the class implementation.
With the offline template compiler I assume this is actually how the generated code will be organized.
Upvotes: 1