Reputation: 293
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:
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.
Upvotes: 4
Views: 3130
Reputation: 1389
First of all, let's understand the concepts behind the @Input
and @Injectable
:
Both is metadata, what its mean ? The architectural takeaway is that you must add metadata to your code so that Angular knows what to do.
(Component Injection) Why @Input
and @Output
?
Input properties usually receive data values. Output properties expose event producers, such as EventEmitter objects.
(Dependency Injection) Why @Injectable
?
@Injectable() marks a class as available to an injector for instantiation. Generally speaking, an injector reports an error when trying to instantiate a class that is not marked as @Injectable().
for more information and examples how you use: @Input @Injectable
Upvotes: 1
Reputation: 3062
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.
Upvotes: 4