I'm looking for an argument on why using @Output
for events is better than passing an @Input
function in Angular 2+.
Using @Input
:
Parent Template:
<my-component [customEventFunction]=myFunction></my-component>
Inside parent-component.ts:
myFunction = () => {
console.log("Hello world")
}
Inside my-component.ts
@Input() customEventFunction: Function;
someFunctionThatTriggersTheEvent() {
this.customEventFunction();
}
Using @Output
:
Parent Template:
<my-component (onCustomEvent)=myFunction()></my-component>
Inside parent-component.ts:
myFunction() {
console.log("Hello world")
}
Inside my-component.ts
@Output() onCustomEvent: EventEmitter<any> = new EventEmitter<any>();
someFunctionThatTriggersTheEvent() {
this.onCustomEvent.emit();
}
Both achieve the same goal, but I think that the @Output
method is more typical from what I've seen in other Angular packages. One could argue that with an Input, you can check to see if the function exists if the event should only be triggered conditionally.
Thoughts?
The advantages of @Output event binding:
onmousemove="doSomething()"
while the @Output event binding is more like calling btn.addEventListener("mousemove", ...)
.