Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: What is the exact difference between private and public attributes in components?

Tags:

angular

Could someone explain the difference between private and not private attributes in components in Angular 2? Like with private_text and other_text in this example:

import { Component } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'my-component',
  template: '<div>{{private_text}}</div><div>{{other_text}}</div>'
})
export class MyComponent {

  private private_text:string;
  other_text:string;

  constructor() {
    this.private_text = "hello";
    this.other_text = "hello";
  }

}
like image 785
Ole Spaarmann Avatar asked Aug 24 '16 09:08

Ole Spaarmann


1 Answers

Public:

Typescript members are public by default.

So if I have a class myClass with the method public myMethod() {} or just myMethod(){} then import my class into another file. I now define in my constructor of another class constructor(my_class: myClass) {}. This now lets me call this.my_class.myMethod() wherever I want in my other class. If it was private. This would not work.

Private:

"When a member is marked private, it cannot be accessed from outside of its containing class"

Really confused why no one has referenced this yet. I think the following link will really help.

https://www.typescriptlang.org/docs/handbook/classes.html#public-private-and-protected-modifiers

like image 55
ian_sawyer Avatar answered Oct 05 '22 23:10

ian_sawyer