Refactor an Angular Smart Component to use a Presentational Component

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson you will learn how to create a presentational component out of an existing smart component to possibly reuse the presentational template in other parts of your angular application.

Learn how to create a smart component in Angular with: Create Smart Components with Angular

Instructor: [00:01] Imagine you have a smart component, and in its template, you're iterating over an array to display the data. What if you make this part of your application reusable? Iterating over an array and displaying some data is a very common use case in an Angular application, but you do not want to duplicate the code.

[00:19] What we can do now is we can separate this code out in the presentational component, and just pass the data in we want to get displayed. This is what we're going to do next. We can open up a console, and just type ngGenerateComponent.

[00:37] Let's call it press, which will generate another component for us. Then we can cut this whole template code out, head over to our presentational component template, and just pass it in here. Because we are binding to a property called data, we have to introduce that in our presentational component, too.

[00:59] Let's head over to our TS file, and add a property called data, which is of the type string array. This time, we are decorating it with the input decorator. Have to import it from Angular core.

[01:21] The presentation component is providing a property called data, and somebody else which uses the presentational component can bind to this property, and pass something from the outside inside this presentational component. This something which gets passed in should be a string array.

[01:41] Let's go to our smart component template, and just use the new presentational component. We are binding to that data property. The presentational component gives us our data, which we get from the service.

[01:55] If we save that, you can see on the right-hand side that Phil, Mike, and Peter are getting displayed again. This time, the smart component only knows where to get the data from, and it passed it to the input property of our presentational component.

[02:10] The presentation component takes the data, and just iterates over it in its own template. Now, this presentational component is reusable in our whole application. We from the outside do not care of how the things are getting displayed.

[02:25] We just use the presentational component, and we pass the data in we want to get displayed. This is how you can refactor an Angular smart component to use a presentational component.