Can you provide reasons why using @Output
for events is more advantageous than passing an @Input
function in Angular 2+?
Utilizing @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();
}
Opting for @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 methods achieve the same outcome, but it seems that the @Output
approach is more commonly used in various Angular packages. Some may argue that with an Input, one can verify if the function exists before triggering the event conditionally.
What are your insights on this matter?