-2

When I use class with private properties in a model and getter/setter I have access to the private property only but not the public one with getter/setter..

https://stackblitz.com/edit/angular-hx3t7g

Why I have '_r' in the ngModel instead of 'r'? How to make it right / should I even do it like this?

3 Answers3

0

This really represents what you wrote in your typescript class Circle.

If you want to have access to the r attribute of Circle, I don't see why you would also have a private attribute.

Your model should just be:

export class Circle {
  C: number;
  r: number;
}
ahbon
  • 502
  • 4
  • 19
  • that is not really helpful...I assume you did not even see the stackblitz. I want to calculate one property - C when model gets r. That is why I use setter for r. – Radek Piekný Mar 30 '19 at 23:56
0

From my understanding, you're computing the value for C when setting r. It looks like your code is correct but it would be better if you change C to be private since you don't really want to access it since its value is computed based on r.

export class Circle {
  private C: number; // make C private
  private _r: number;

  set r(value: number) {
    this.C=2*3.14*value;
    this._r = value;
  }

  get r(): number {
    return this._r;
  }
}

Since _r is private, you won't be able to access it outside the class and the only way to change it is to use r.

Joshua Robles
  • 151
  • 1
  • 8
0

So I found what I was looking for..If anyone google this as well: https://stackblitz.com/edit/angular-mkncdh

you define a property that you want private and then set it to enumerable = false as you can see in circle.ts. It got a little bit more complicated than I wanted but does exactly what I want. Now you can see in the output that in ngModel there are only those public properties :)

  • FYI. This is essentially the same thing the typescript transpiler [outputs](https://www.typescriptlang.org/play/index.html#src=export%20class%20Circle%20%7B%0D%0A%20%20C%3A%20number%3B%0D%0A%20%20private%20_r%3A%20number%3B%0D%0A%20%20set%20r(value%3A%20number)%20%7B%0D%0A%20%20%20%20this.C%3D2*3.14*value%3B%0D%0A%20%20%20%20this._r%20%3D%20value%3B%0D%0A%20%20%7D%0D%0A%20%20get%20r()%3A%20number%20%7B%0D%0A%20%20%20%20return%20this._r%3B%0D%0A%20%20%7D%0D%0A%7D) – Mathias W Mar 31 '19 at 12:32