0

I have created many variables and accessing it in respective template/html. By default, all variables will be public. and these public variables is problematic, so i want to convert them to private. but, as soon as I am converting these private variables to public, I am getting error of private members cannot be used outside the class. conceptually, it is absolutely correct. But, in component, template/html and *.ts files belongs to same thing, correct me if i am wrong. then, why can't I use private variables created in ts file to corresponding template/html?

if both ts file and html/template file are separate then, how can i access private variable in html?

I am using typescript.

  1. converted public variables to private in ts file
  2. use private variables in html of same component

test.component.ts

public myVar = 'iCreatedThisVariable';

          to

private myVar = 'iCreatedThisVariable';

test.component.html

<p>{{myVar}}</p>

I should be able to use private variables in html, if both ts file and html belong to the same class.

If they are different, then how can I use private variables in html using angular2+?

ngWolf
  • 307
  • 1
  • 6
  • 21

1 Answers1

0

AoT compiler in Angular requires you to have public members in controller classes when you want to use them in your templates. Because public/private concept doesnt exist when the TypeScript code gets compiled down to ES5.

Access modifiers should be used when you are doing component composition and or encapsulation, not when you are doing templates and controllers.

If you want to encapsulate the controllers variables, but still want to access some data or set it, you should create corresponding methods say getters/setters.

Vilius K.
  • 5
  • 3