我正在寻找关于为什么使用@Output
事件比@Input
在 Angular 2+ 中传递函数更好的论点。
使用@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 包中看到的更典型。有人可能会争辩说,使用输入,您可以检查该函数是否存在,如果事件只应有条件地触发。
想法?