Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what kind of Access Modifier should I give to a template acessible method in Angular?

Tags:

angular

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?

like image 333
Efim Rozovsky Avatar asked Oct 20 '25 08:10

Efim Rozovsky


2 Answers

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.

like image 148
GreyBeardedGeek Avatar answered Oct 23 '25 01:10

GreyBeardedGeek


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.

like image 28
Kurt Hamilton Avatar answered Oct 23 '25 00:10

Kurt Hamilton