Angular2 why use @Output over @Input for callbacks

I am learning Angular2, after working with Angular1 for several years. I am creating a component of a credit card form, with the main goal to learn a few key concepts in Angular2. The component should handle all formatting and return a Stripe token through a callback. I realized that I can handle callbacks in two ways.

Using the @Output Option

In my component, I define the output variable and use it as in this example:

export class CreditCardForm{ .... @Output () callback = new EventEmitter(); .... doCallback(){ this.callback.emit({data: 123}); } } // Parent view <credit-card-form (callback)="creditCardCallback($event)"></credit-card-form> 

Using the @Input Variable

However, I could just pass the callback method ( creditCardCallback used in the parent template) to the input variable, for example:

 export class CreditCardForm{ .... @Input () callback; .... doCallback(){ this.callback({data: 123}); } } // Parent view <credit-card-form [callback]="creditCardCallback"></credit-card-form> 

Question

Why do I want to use @Output over @Input ? What can I do using @Output variables @Output ? As far as I can see, this just adds overhead due to the use of the EventEmitter class.

+7
angular typescript
source share
2 answers

There is always more than one way to trick a cat. However, in my opinion, using @Output has the following advantages:

  • Code reading: it is easier to use the data stream if you use the recommended style.

  • De-communication: for example, for a regular @Output event, in the ParentComponent , you can have more flexibility when processing the dispatched event:

  • Last but not least, it allows the banana in the window syntax: say in ChildComponent :

@Input() creditCardValue: string; @Output() creditCardValueChange: EventEmitter<string>;

Then you can have two-way binding in the ParentComponent easily:

 <credit-card-form [(creditCardValue)]="creditCardVal"></credit-card-form> 
+7
source share

Imho, @Output - A HUGE design flaw , as you cannot respond to the result or its processing. One example of this drawback is the click of a button. When you click the button, you need to turn off 99% of cases when the action occurs. After the action is completed, the button should be turned on again. This is what you want to handle in the element itself, and not in the parent. With @Output you cannot do this. Using an action function like @Input , you can do it! And if your action function returns Observable or Promise, you can easily wait for it. Creating a custom directive that handles this trip is easy, and so you can use [click] everywhere, and it will behave that way.

EDIT: I am not saying that @Output not using it, but not for actions you need to wait, etc. Naming your @Input well also clarifies the thread, like onDelete , etc ...

-one
source share

All Articles