Angular2 why use @Output over @Input for callbacks

后端 未结 2 932
一向
一向 2021-01-04 08:01

I am learning Angular2, after working with Angular1 for a couple of years. I\'m creating a credit card form component, with the main goal to learn a couple of key concepts i

相关标签:
2条回答
  • 2021-01-04 08:03

    There are always more than one way to skin the cat. However, in my opinion, using @Output has these benefits:

    • Code readability: It's easier to know the flow of data if using the recommended style.

    • De-coupling: For example, for normal @Output event, in your ParentComponent, you can have more flexibility of handling the dispatched event:

    • Last but not least - it enables banana in the box syntax: Say in your ChildComponent you have:

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

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

    <credit-card-form [(creditCardValue)]="creditCardVal"></credit-card-form>
    
    0 讨论(0)
  • 2021-01-04 08:29

    Imho, @Output is a HUGE design flaw, as you can't react to the result, or handling of it. The number one example of this flaw is the click of a button. When clicked, the button should be disabled 99% of the cases when the action is taking place. Once the action is done, the button should be enabled again. This is something you want to handle in the element itself, not in the parent. With @Output, you can't do this. Using an action function as @Input, you can do this! And if your action function returns an Observable or Promise, you can easily wait for it. Creating a custom directive that handles this disabling is easy, and thus you can use [click] everywhere and it will behave that way.

    EDIT: I don't say @Output doesn't have it's uses, but not for actions you need to wait on etc.... Naming your @Inputs good, also clarifies the flow, like onDelete etc...

    0 讨论(0)
提交回复
热议问题