Angular is mostly about Typescript classes, and Typescript classes have modifiers that alter the visibility of class members: public
, protected
, private
, and readonly
. Here is what you need to know about them.
Everything is public by default
If you don’t use a modifier on a class member, it is public by default. Any other class can see and use that member and change its value:
private
means that the member isn’t visible outside of the class (including a component’s HTML template)
private
is a way to enforce that other classes cannot access a member of your class. Used in a component, this indicates that we do not want that property to be used in the component’s HTML template. In a service, this suggests that we don’t want other components/services to see that member:
protected
is in-between public
and private
. It makes the member accessible in a component’s template without making it fully public.
In the following example, our component property date is invisible from other Angular code in our app, but our HTML template can use it:
Best practice – My recommendation
If you want to stick to simple rules that make sense and are the safest, here’s what you can do:
- Make every member
private
by default - If the member is needed in the template of a component, make it
protected
- If the member is meant to be fully public, go with
public
Tomorrow, I’ll add a couple more suggestions by introducing the readonly
modifier. Stay tuned!