Reputation: 5870
Learning Angular 2 and trying to understand when I should use a component input/output and when I should better update a service property (possibly attached with an EventEmitter if updates are needed).
I have a list of, say, tasks, and each list items shows various info and options for this list item. This list works in the way that only one list item is active, and the active one is on the top of the list. One of those options for each list item is to activate it (if it is not already active), but other components could also possibly change which is the active item.
I have a parent task
component, list
component and a list-item
component (and some other related components), and in addition I have a task-service
.
The main task
component could use list
component (and something-realted
component, many of the components used needs to know and possibly change the activeItemId
), like this:
<list [(active-item-id)]=“activeItemId”></list>
<something-related [(active-item-id)]=“activeItemId”></something-related>
The list
component could use list-item
this way (active
is a pipe and also a property on item):
<list-item *ngFor=“#item of items | active”
(item)=“item”
[(active-item-id)]=“activeItemId”>
</list-item>
But since I have a task-service
that contains various task related, I could on the service use the already existing activeItemId
-property (that has an eventemitter), and all the various task-components could just get info (and be updated) via this property, instead of “sending” the property back and forth via various components via inputs/outputs.
When would it be appropriate to just use a service for something like this and when would it be appropriate to use input/outputs for components instead?
Upvotes: 3
Views: 1561
Reputation: 5870
Got a great answer via Angular Google Groups:
Without reading your full explanation, I'd say use binding if possible, otherwise use a shared service.
Binding is not possible when - the two components aren't direct parent/children - the component is added by the router - the component is added by DynamicComponentLoader
If you share the data between several components at once it might be easier to not use binding even when one or some of them are direct children.
Thank you, Günter!
Upvotes: 5