Quantcast
Viewing latest article 1
Browse Latest Browse All 9

Answer by Cosmin Popescu for Angular2 - should private variables be accessible in the template?

I know that this is a little late, but I've been preocuppied with this problem even since Angular2 and finally I've come up with a nice workaround to allow me to have nice proper components API's and also to be able to access private fields in them from templates with proper type checking:

export interface MyComponentPrivateProperties {    _label: string;}export class MyComponent {    private _label: string = 'Label';    public get view(): MyComponentPrivateProperties {        return this as any;    }}
<div>{{view._label}}</div>

In this way, as you can see, we will have even type checking and all we need in the html template and also a proper API of the component. If in another component we reference the MyComponent class like this:

export class OtherComponent {    private _m: MyComponent;    ngOnInit() {        // here, this._label is not visible.    }}

we will notice the property _label is not visible.

Of course, notice that the class MyComponent should not implement the interface MyComponentPrivateProperties. There will be no implementation for this interface. This is just a description for the angular ngc compiler. It tells the compiler at compile time which are the private properties that should be accessible from the templates and then dissapears at run time.


Viewing latest article 1
Browse Latest Browse All 9

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>