我正在寻找一个争论,为什么在事件中使用@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包中看到的更为典型.有人可能会说,使用输入,如果只能有条件地触发事件,您可以检查函数是否存在.
思考?