0
   <ng-container *ngFor="let child of root.getChildren()">
   <ng-container id="prefix" *ngIf="hasPrefix(child)">
   {{getPrefix(child)}}
   </ng-container>
   </ng-container>

I am just learning angular. I don't have much experience with angular. Please feel free to correct me if I am wrong.

I have a tree data structure, where I have to traverse through the tree and print the prefix of child nodes. But the prefix is a private property. What is the best practice in angular to access the private properties in the view component? The above code leads to multiple method calls as there will be a change detected during recursion.

Thanks in advance.

Teja
  • 25
  • 5
  • 1
    In any proper OOP you are not supposed to access any private property outside the class itself. If you want that value to be publicly available, expose it via a getter. – Mike Doe Oct 19 '18 at 13:40
  • 2
    Possible duplicate of [Angular2 - should private variables be accessible in the template?](https://stackoverflow.com/questions/34574167/angular2-should-private-variables-be-accessible-in-the-template) – bugs Oct 19 '18 at 13:40
  • I am trying to access the private property using getter but the getter method is called more than once as there is change detected during recursion. Could some one suggest some best practice? – Teja Oct 19 '18 at 13:42
  • You shouldn't worry about that until problem faced. And then, probably, you will start working with changeDetecteionStrategy first. And only if this will not help, you, may be, will start doing something with getters. SO just don't worry right now – Drag13 Oct 19 '18 at 13:45

2 Answers2

0

Ideally you should not use your private properties outside the controller. If you want to use them in view, may be declare them as public.

alokstar
  • 499
  • 2
  • 7
0

If I understand you correctly, you access some private field using public getter. This is ok and not a problem. Yes, it cause some overhead because getter's invocationes but you should not worry about this right now. The reason for this is that DOM manipulations (that also happen very often) are much more expensive and this overhead will be very small.

So this code is ok:

class MyController {
    private _model: object;
    public get name() {return this._model.name;}
}

And if you start facing performance issue, the first question should be asked is - how often my DOM renders, but not how often my getter called.

Drag13
  • 5,859
  • 1
  • 18
  • 42