Reputation: 33
Let's say we have an angular component that is pretty much a styled button that we're going to use throughout the app. What is the right way to pass a click handler to that component? Because as far as I know there are two ways to do it.
1. We simply pass it to the component's selector like so
<app-styled-button (click)="handleClick()"></app-styled-button>
2. We use the
@Input() onClick
then
<app-styled-button onClick="handleClick()"></app-styled-button>
and then in the styled button template
<button (click)="onClick()">
...
</button>
I've done some basic testing and it seems to be working fine with both approaches, but are there any benefits from using one over the other? I mean the first option uses much less code but the second somehow feels like the right way to do it. I am however new to angular so I'm still calibrating my moral compass :D
Upvotes: 0
Views: 2620
Reputation: 4110
In your first case, you are listening to the click event rised on your component instead of you button. This is not the same event, the event parameters will not be the same.
I suggest you to pass the button click event through you component.
In this case, you have to use @Output
instead of @Input
to pass the event. Please take a look at the official documentation: https://angular.io/guide/component-interaction#parent-listens-for-child-event
I've created a simple example: https://stackblitz.com/edit/angular-tps7zk
Upvotes: 2