I have a parent component, a child component and a service. The parent component subscribes an object data from the service. The child component needs to listen for that data change too. Which is better, child component gets data from its parent using @Input or let it subscribe to the service too?
Asked
Active
Viewed 480 times
2
-
It's up to you. The main difference between passing data with an `@Input` instead with a `Subject` (or BS), is the control you have on the child component update. – Jacopo Sciampi Jan 29 '20 at 08:34
-
There is no `better`. Just choose what you prefer. – Carsten Jan 29 '20 at 08:40
-
Assuming parent is a smart component and child is a dumb component (and ideally reuseable) you should use @Input because its unlikely you want the child to have access to the other methods in your service. – Andrew Allen Jan 29 '20 at 08:42
3 Answers
2
Use cases for @Input()
- When we have only one to two hierarchy
- When the value we are passing is been used by other components
Use cases for Service
- When we have a lot of hierarchy down and passing the values becomes a bit tough
- When some component functionality depends on some component value which may be some 10 hierarchies down, so in that case we can use Subscribe to service so whenever the value changes we can automatically use it in our component
- When a value is used by more than a single component

Gvs Akhil
- 2,165
- 2
- 16
- 33
1
If service is providing the exact data in desired format, then subscribing to service directly is a better than depending on parent component. That will reduce the overall complexity of the code and also improve performance.
Parent component can be used as a wrapper or proxy in these scenarios:
Service is not providing data in the exact format required by child components.
Lot of child components rely on same data provided by service.
Child component needs data aggregated from multiple services.

Gopinath
- 4,066
- 1
- 14
- 16
1
@Emmanuel Sayson It depends on the use case if you are not updating the data on parent then better to use service. Service is more clear in nested hierarchy

Deepak Patidar
- 384
- 1
- 8
- 23