Angular 2 Smart Components vs Presentation Components

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 4 years ago

Both Smart Components and Presentation Components receive data from Services in entirely different ways. Smart Components use constructor injection to lookup the entire service from the injector while Angular 2 Presentation components take the data from @Input defined on their component class.

[00:00] With our simple service in place, I can now render out things off of that simple service. We'll just render out simple-service.message, and you'll see that message we declared on it, "Hello, from the simple service," if I navigate to that, that's just this message here.

[00:18] This is pretty typical of a smart container, is being able to inject services that are declared within your application, things that are specific to your application, and creating these couplings between modules and your views.

[00:32] For presentation components -- I'll bring back in Widget 1 -- instead of injecting things through the constructor, we're actually going to pass it in through an input. I'll say message is equal to simple-service.message. Now if I navigate to my Widget 1, and I'll set up an input here, call this message, and then use the message in my template.

[01:02] Let's just say Juan's message, then an H3 of message. If you look in my home component, you'll see the simple service message here, as well as being passed into my widget here. I'll hit save, and you'll see the message from my service rendered out in my template, and it's also rendered out in this component -- this Widget 1 that we created.

[01:26] The main difference here is that, in Widget 1, there is no reference to that service's module. In fact, inside of this entire widget module, there's no reference to that service's module. It's completely decoupled from our application. This makes it a pure...basically, what's called a presentation component.

[01:43] Whereas, in my home component, which is coupled to my application, because it knows about this service's module -- granted it knows as little about it as possible, but it still knows about it. With my Widget 1, I could actually pass in a string, say "Hello, world!" I'll hit save here.

[02:00] Now we have one Widget 1 and another Widget 1, using different data, completely. Again, that's because it's completely decoupled. It's not working from the constructor. It's simply working from the idea of having inputs, where you pass your data in, versus passing your services and data in through a constructor.

[02:17] Presentation components use inputs for passing data in, and these smart containers use the constructor for dependency injection to pass the services in.