Search code examples
javascriptangularweb-componenteventemitterviewchild

What's the 'Angular way' of a child updating a parent?


There seems to be a few ways of skinning this cat, but I want to know the best (practice) and why.

If I want to collect some data in child-cmp and pass it to parent-cmp, I can:

  • Wrap an object with a function from parent and pass it as an input to child, calling the function on the input.
  • Make an EventEmitter function in child-cmp and emit the result, collecting the data in parent-cmp.
  • Access the child through @ViewChild() and directly call it's methods.
  • Create an ngModel (only if in a form?) with the data to be collected

I'm sure there's more. I feel like using the Event emitter is the most Angulary thing to do, for a non form based component. But I can't really explain why with a good technical foundation. Thoughts?


Solution

    • @Output() is the first thing to choose for connecting a child with a parent, when there are no specific reasons for other options.
      It creates the least amount of coupling between the components. If you want to use the child in another parent component, this is the easiest way. This is all what Angular components are - reusability.

    • A shared service is another option, especially when there is no direct parent child relation.

    • *ngModel (implementing ControlValueAccessor in the child component) is a good idea if the component should be used in forms.

    avoid

    • Acquiring a reference of the child using @ViewChild() makes the parent dependent on the child component implementing a specific interface.

    • Wrap an object with a function (or otherwise passing method or object references)
      passing methods around introduces strong coupling. Use rather a shared service. A shared service also is a class instance with a method, but it's a standard way in Angular every developer is used to, and it's more explicit. To push updates to participating components, use