I'm trying to make my Angular application to be as straight forward readable to other programmers, and I came to this dilemma, I have an method within my component:
onAddPost(): void {
console.log('adding a post!');
}
I want to invoke it on click from a button from my template(of the same component):
<button (click)="onAddPost()">Save Post</button>
so far so good, but then I want to give Access Modifier for running the "onAddPost" only within the given component, and nothing seems to work.
private onAddPost(): void {
console.log('adding a post!');
}
gives me the error of:
"Property 'onAddPost' is private and only accessible within class 'PostCreateComponent'"
I get something similar for 'protected', can someone help me understand what am I missing about Angular? why the template is not part of the component class? and can I limit the access for the methods used in my component?
AS @kurt-hamilton's answer says, the method must be public to be accessible to the template.
Personally, this irks me too. I too would prefer a way to make methods and properties of the Component available only to the template. Unfortunately, there's no way that I know of to do that.
What I have done for the sake of clarity is to declare an interface with the methods and properties that are to be exposed to the template, and then have the Component implement the interface.
With some extra effort, you can make the Component's methods and properties private, and expose them in the interface (public).
Finally, the Component has a public 'getter' for 'view', which simply returns the Component's 'this' pointer.
So, then the template accesses the methods and properties of the Component through the interface, as in, e.g. (click)=view.onClick($event)
It doesn't stop anything in the template from accessing things directly, but if you use this pattern consistently, it becomes obvious when the template is doing direct access instead of going through the interface.
You may or may not feel that this is worthwhile, YMMV. Personally, I found it to be a bit on the heavy side, and stopped using the pattern.
You don't need to give a function an access modifier - it is public by default. You could explicitly add the public
access modifier.
public onAddPost(): void {
console.log('adding a post!');
}
All access modifiers are lost when the Typescript is compiled to Javascript anyway. private
access is just a Typescript construct that helps you at design time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With