Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input vs Injectable in Angular 2

Tags:

angular

When should you use @Input vs an @Injectable in an Angular 2 project? For example, if I have an object (with no methods) that multiple components make changes to, I can either:

  1. Bind the object to the other components with an input binding
  2. Put the object in its own class and add @Injectable then inject it into the components that need to make changes to it.

How do you decide which way to go? Especially since with Injectables you don't have to deal with the hierarchy of how to pass the input data to the child component.

like image 627
zebraco Avatar asked Oct 30 '25 15:10

zebraco


1 Answers

Unless its a very simple object, I would almost always lean towards using an Injectable class and dependency injection. Inputs aren't resolved until the first ngOnInit() lifecycle hook so at the very least an Injectable class will provide more predictable behavior. Creating chains of inputs to pass something down multiple levels is a good sign you should use a service / injectable instead. Using an injectable class you can just inject it wherever you need it without having to worry about the parent component having it as well.

like image 106
diopside Avatar answered Nov 02 '25 09:11

diopside



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!