【发布时间】:2018-06-02 03:55:46
【问题描述】:
我正在寻找一个论据,说明为什么在事件中使用 @Output 比在 Angular 2+ 中传递 @Input 函数更好。
使用@Input:
父模板:
<my-component [customEventFunction]=myFunction></my-component>
在 parent-component.ts 中:
myFunction = () => {
console.log("Hello world")
}
在 my-component.ts 中
@Input() customEventFunction: Function;
someFunctionThatTriggersTheEvent() {
this.customEventFunction();
}
使用@Output:
父模板:
<my-component (onCustomEvent)=myFunction()></my-component>
在 parent-component.ts 中:
myFunction() {
console.log("Hello world")
}
在 my-component.ts 中
@Output() onCustomEvent: EventEmitter<any> = new EventEmitter<any>();
someFunctionThatTriggersTheEvent() {
this.onCustomEvent.emit();
}
两者都实现了相同的目标,但我认为 @Output 方法比我在其他 Angular 包中看到的更典型。有人可能会争辩说,使用 Input,您可以检查该函数是否存在,如果该事件仅应有条件地触发。
想法?
【问题讨论】:
-
这里有什么问题?
-
为什么要使用输出而不是输入进行事件绑定,反之亦然?
-
一个原因是许多订阅者可以处理 Output 事件,而只能为 Input 属性提供一个处理程序。
-
@ConnorsFan 嗯,我没想到。如果您愿意,我很乐意接受这个作为答案,但需要更详细一点。
标签: angular typescript angular2-components angular5 typescript-decorator