1
What Are The Tradeoffs Between @Output() x: EventEmitter & @Input() callback: Function?


As the first step I took toward finding a solution, I had thoroughly read Angular2 why use @Output over @Input for callbacks. The title seems to ask the same question, though, the question within is rather shallow in acceptance criteria and my question is looking for more detail. Please see below for such detail.

There are [at least] 3 ways to accomplish Child-to-Parent Communication in Angular++ (not 1.x), but to better implement the 3rd option I am concerned with only 2 of these for the question:

Using EventEmitter as an @Output
@Output() onEvent: EventEmitter<any> = EventEmitter<any>();
Using a Callback as an @Input
@Input() handleEvent: Function = new Function();
  • Are @Outputs automatically optional parameters/properties?
  • Do @Outputs signal anything helpful to Angular under the hood?
  • Are there Garbage Collection concerns for either?
In general, what are the tradeoffs between these 2 approaches?
Cody
  • 9,785
  • 4
  • 61
  • 46

1 Answers1

5

@Outputs are streams of data. They are essentially Observables with some extra jazz on them. Angular is not (immediately) concerned with the data being emitted. Angular will internally use Output hooks to run change detection, and are primarily used as child-to-parent communication hooks.

@Inputs are property bindings. Angular does more under the hood to manage change detection with inputs, the behavior of which can be altered with the ChangeDetectionStrategy. @Inputs must also be resolved by the component before a component's lifecycle hooks begin firing. @Inputs are primarily used as parent-to-child communication.

Setting an event handler to an @Input is not considered good practice, and is against the Angular style guide. Angular already runs change detection on @Input properties and compares when the property value changes. Setting the input to a function (and binding the property to a function) can cause change detection to be unpredictable. Instead, use getters and setters on @Inputs or use ngOnChanges hooks to perform logic off property binding changes.

There are also use cases to combine @Outputs and @Inputs to a single property (e.g banana-in-a-box syntax like [(ngModel)] ).

If you use Angular's API as documented and recommended, there should be no concern for memory leaks. You are still responsible for cleaning up other subscriptions on component destruction, however.

joh04667
  • 7,159
  • 27
  • 34
  • Fantastic answer. This covers most of what was needed to validate/invalidate my intuitions for my implementation. Thank you. – Cody Mar 09 '18 at 21:28