Angular2为什么在@Input上使用@Output进行回调 [英] Angular2 why use @Output over @Input for callbacks
问题描述
与Angular1合作几年后,我正在学习Angular2.我正在创建一个信用卡表单组件,其主要目标是学习Angular2中的几个关键概念.该组件应处理所有格式,并通过回调返回Stripe令牌.我意识到我可以通过两种方式处理回调.
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 in Angular2. The component should handle all formatting, and return a Stripe token through a callback. I realised that I can handle callbacks in two ways.
使用@Output参数
在我的组件中,我定义了一个输出变量,并像下面的示例一样使用它:
In my component I define a output variable and use it like 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>
使用@Input变量
但是,我可以将回调方法(在父模板中使用的creditCardCallback
)传递给输入变量,如下所示:
However, I could just pass the callback method (creditCardCallback
, used in the parent template) to an input variable, like this:
export class CreditCardForm{
....
@Input () callback;
....
doCallback(){
this.callback({data: 123});
}
}
// Parent view
<credit-card-form [callback]="creditCardCallback"></credit-card-form>
问题
为什么我要在@Input
上使用@Output
?通过使用@Output
变量可以实现什么?据我所知,这只能通过使用EventEmitter
类来增加开销.
Why would I want to use @Output
over @Input
? What do I achieve by using @Output
variables instead? As far as I can see, this just adds an overhead by having to utilise the EventEmitter
class.
推荐答案
总是有不止一种为猫皮的方法.但是,我认为使用@Output
有以下好处:
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.
去耦:例如,对于普通的@Output
事件,在您的ParentComponent
中,您可以具有更大的灵活性来处理分派的事件:
De-coupling: For example, for normal @Output
event, in your ParentComponent
, you can have more flexibility of handling the dispatched event:
最后但并非最不重要-它在框式语法中启用了香蕉:说在ChildComponent
中,您拥有:
Last but not least - it enables banana in the box syntax: Say in your ChildComponent
you have:
@Input() creditCardValue: string;
@Output() creditCardValueChange: EventEmitter<string>;
@Input() creditCardValue: string;
@Output() creditCardValueChange: EventEmitter<string>;
然后,您可以轻松地在ParentComponent
中进行双向绑定:
Then you can have two-way binding in your ParentComponent
easily:
<credit-card-form [(creditCardValue)]="creditCardVal"></credit-card-form>
这篇关于Angular2为什么在@Input上使用@Output进行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!